封装倒计时自定义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>
相关推荐
BigTopOne3 分钟前
VS Code IntelliSense 配置(解决 #include 找不到的报红)
前端
愚公搬代码6 分钟前
【愚公系列】《Web应用安全》005-Visual Studio Code编辑器的使用
前端·安全·编辑器
用户921080262869 分钟前
2. 以 Bubble 为例,看 Ant Design X Vue 组件是怎么设计的
前端
Liora_Yvonne11 分钟前
Monorepo 里的 shared、services 和 ui 到底怎么划分?
前端
PedroQue9914 分钟前
uni-router v2.1.0 升级:导航守卫全面支持返回值模式
前端·uni-app
猫七先生17 分钟前
从零到一:个人博客自动化部署踩坑全记录
前端
淼澄研学20 分钟前
Python调用通义千问API实现长尾搜题内容自动化生成实战
前端·react.js·架构
绿岛之北21 分钟前
Electron 安全入门:为什么一个 XSS 可能变成 RCE?
前端·electron
舒灿29 分钟前
DeepSeek Harness——Agent自我进化的实现途径?
前端·ai编程·deepseek
嘟嘟071731 分钟前
顺时针螺旋填充 n×n 矩阵:手撕 generateMatrix 的四个 for 循环
javascript·算法·面试