封装倒计时自定义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>
相关推荐
前端之虎陈随易11 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·vue.js·人工智能·typescript·node.js
一路向北he11 小时前
字节钢铁军团--“提供情境,而非控制”
java·开发语言·前端
kyriewen12 小时前
豆包和千问同时关了智能体,我用它们搭的 3 个自动化全废了——迁移方案整理
前端·javascript·ai编程
前端一小卒12 小时前
我用 TypeScript 从零手写了一个 Claude Code,然后发现它的核心只有 30 行
前端·agent
铁皮饭盒12 小时前
用 Bun.cron 定时 7 月 7 日,为啥? 看图1
javascript
大圣编程13 小时前
Python中continue语句的用法是什么?
开发语言·前端·python
yuhaiqiang13 小时前
随手 vibecoding 的浏览器插件已经 6000 多次下载,聊聊他的产品设计
前端·后端·面试
之歆14 小时前
Vue商品详情与放大镜组件
前端·javascript·vue.js
再吃一根胡萝卜15 小时前
如何把小米 MiMo 接入 CodeBuddy,打造私有 Agent
前端
负责的蛋挞16 小时前
异步HttpModule的实现方式
java·服务器·前端