封装倒计时自定义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>
相关推荐
槁***耿1 分钟前
前端路由守卫
前端
百***35483 分钟前
前端视频处理开发
前端·音视频
顾安r16 分钟前
11.29 脚本游戏 单页面格斗游戏模板
前端·javascript·css·游戏·virtualenv
g***557517 分钟前
Redis 通用命令
前端·redis·bootstrap
爱睡觉的雨21 分钟前
跨域问题(前端)
前端
我叫张小白。21 分钟前
Vue3 路由:单页面应用的核心引擎
前端·javascript·vue.js·前端框架·vue3
y***866925 分钟前
前端PWA应用特性使用指南
前端
天空陪伴星辰a28 分钟前
表单校验问题
前端·javascript·表单校验
鱼鱼块1 小时前
《最小栈的巧妙设计:用辅助栈实现 O(1) 获取最小值》
javascript·算法·面试
San301 小时前
反转字符串与两数之和:两道简单题背后的 JavaScript 思维深度
javascript·算法·面试