封装倒计时自定义react hook

ts 复制代码
import { useEffect, useState, useRef } from 'react'

const useCountDown = (initialTime = 60) => {
  let timerRef = useRef<any>(null)
  const [countdown, setCountdown] = useState(initialTime);
  const [isCounting, setIsCounting] = useState(false);

  const startCountDown = () => {
    if (!isCounting) {
      setCountdown(initialTime)
      setIsCounting(true)
      timerRef.current = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timerRef.current)
            setIsCounting(false)
            return initialTime
          }
          return prev - 1
        }
        )
      }, 1000)
    }
  }

  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  return {
    countdown,
    isCounting,
    startCountDown
  }
}

export default useCountDown

使用

ts 复制代码
  const {
    countdown,
    isCounting,
    startCountDown
  } = useCountDown()
  
 const handleGetCode = () => {
    if(isCounting)return
    startCountDown()
  }
  
  ...
  
<AtButton type='primary' onClick={handleGetCode}>{isCounting ? `${countdown}秒后重试` : '获取验证码'}</AtButton>
相关推荐
deli00716 分钟前
配色对比度检查器:一眼看清文字和背景谁看不清
前端
梦诺17 分钟前
vue3 keepAlive+记录滚动条
前端·javascript·vue.js
葡萄城技术团队20 分钟前
SpreadJS V19.2 新特性揭秘:甘特表的进度线
前端
计算机魔术师39 分钟前
黄仁勋台上接特朗普电话开免提,全场听到一句话:AI 不会减速
前端
yivifu1 小时前
HTML元素的textContent和innerText两个属性的差别
前端·html
天若有情6731 小时前
开源轻量双语工具|一键批量查询 NPM 包历史下载量,支持按作者批量统计
javascript·npm·github pages·开源工具·netlify·前端开源·npm克隆量
咸鱼老弟1 小时前
Speculative Decoding(投机采样):大模型"先猜后验",生成速度翻倍
前端·算法·ai编程
a1117762 小时前
网页版「MATLAB」开源
前端·开源
JianZhen✓2 小时前
解决SPA发版旧版本残留+动态路由打包失效的完整方案(附落地代码)
前端·状态模式
计算机魔术师2 小时前
Dario Amodei 发文呼吁放缓前沿 AI 开发后各方表态汇总
前端