封装倒计时自定义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>
相关推荐
li35743 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj4 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel4 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel4 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
^Rocky5 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
西陵5 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld6 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
笑鸿的学习笔记6 小时前
JavaScript笔记之JS 和 HTML5 的关系
javascript·笔记·html5
东风西巷7 小时前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求