封装倒计时自定义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>
相关推荐
weixin_4643076311 分钟前
设置程序自启动
前端
小满zs16 分钟前
Next.js第十七章(Script脚本)
前端·next.js
小满zs1 小时前
Next.js第十六章(font字体)
前端·next.js
喝拿铁写前端6 小时前
别再让 AI 直接写页面了:一种更稳的中后台开发方式
前端·人工智能
A向前奔跑7 小时前
前端实现实现视频播放的方案和面试问题
前端·音视频
十一.3668 小时前
131-133 定时器的应用
前端·javascript·html
xhxxx8 小时前
你的 AI 为什么总答非所问?缺的不是智商,是“记忆系统”
前端·langchain·llm
3824278279 小时前
python:输出JSON
前端·python·json
2503_928411569 小时前
12.22 wxml语法
开发语言·前端·javascript