封装倒计时自定义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>
相关推荐
lecepin27 分钟前
AI Coding 资讯 2025-09-17
前端·javascript·面试
IT_陈寒29 分钟前
React 18实战:7个被低估的Hooks技巧让你的开发效率提升50%
前端·人工智能·后端
树上有只程序猿1 小时前
终于有人把数据库讲明白了
前端
猩兵哥哥1 小时前
前端面向对象设计原则运用 - 策略模式
前端·javascript·vue.js
司宸1 小时前
Prompt设计实战指南:三大模板与进阶技巧
前端
RoyLin1 小时前
TypeScript设计模式:抽象工厂模式
前端·后端·typescript
华仔啊1 小时前
Vue3+CSS 实现的 3D 卡片动画,让你的网页瞬间高大上
前端·css
江城开朗的豌豆1 小时前
解密React虚拟DOM:我的高效渲染秘诀 🚀
前端·javascript·react.js
前端人类学1 小时前
React框架详解:从入门到精通(详细版)
react.js·redux