封装倒计时自定义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>
相关推荐
Hyyy17 小时前
理解LLM的基本工作原理:预训练、微调、推理的区别
前端
Gatlin17 小时前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战
前端
代码煮茶17 小时前
React 组件封装方法论 —— 以 Todo App 为例
javascript·react.js
Pedantic17 小时前
本地通知(Local Notifications)学习笔记
前端
任沫17 小时前
Agent之Function Call
javascript·人工智能·go
森蓝情丶18 小时前
我给 AI 搭了个法庭:一个前端仔的 LangGraph 实战全记录
前端·后端
爱勇宝18 小时前
干了近 8 年,一夜之间被裁:AI 时代,程序员最该害怕的不是 AI
前端·后端·程序员
Pedantic18 小时前
Combine 框架学习笔记
前端
runnerdancer18 小时前
Agent如何加载执行Skill的脚本
前端·agent
yingyima19 小时前
VS Code 正则替换技巧:从凌晨3点的服务器报警开始
前端