封装倒计时自定义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>
相关推荐
飞羽殇情19 分钟前
基于React Native鸿蒙跨平台开发构建完整电商预售系统数据模型,完成参与预售、支付尾款、商品信息展示等
react native·react.js·华为·harmonyos
摘星编程19 分钟前
React Native + OpenHarmony:ImageSVG图片渲染
javascript·react native·react.js
会编程的土豆1 小时前
新手前端小细节
前端·css·html·项目
摘星编程1 小时前
OpenHarmony + RN:Text文本书写模式
javascript·react native·react.js
广州华水科技1 小时前
单北斗GNSS在桥梁形变监测中的应用与技术进展分析
前端
我讲个笑话你可别哭啊1 小时前
鸿蒙ArkTS快速入门
前端·ts·arkts·鸿蒙·方舟开发框架
CherryLee_12101 小时前
基于poplar-annotation前端插件封装文本标注组件及使用
前端·文本标注
特立独行的猫a1 小时前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
周航宇JoeZhou1 小时前
JB2-7-HTML
java·前端·容器·html·h5·标签·表单
代码小库1 小时前
【课程作业必备】Web开发技术HTML静态网站模板 - 校园动漫社团主题完整源码
前端·html