useCountDown (React Hooks)倒计时

javascript 复制代码
import { useState, useRef } from "react";
import "./styles.css";

/**********************************************************
 * 补全 useCountDown (React Hooks)倒计时的功能
 **********************************************************/

// 请补全,返回:
// count     当前剩余秒数
// start()   开始
// reset()   重置
// isRunning 是否在运行
function useCountDown(options) {
  const {
    total, // 总秒数
    onEnd, // 倒计时结束回调
  } = options;

  const [count, setCount] = useState(total);
  const countRef = useRef(total);

  const [isRunning, setIsRunning] = useState(false);

  const start = () => {
    reset();
    const updateCount = () => {
      if (countRef.current <= 0) {
        setIsRunning(false);
        onEnd();
        clearInterval(timer);
        return;
      }

      setIsRunning(true);
      setCount((count) => count - 1);
      countRef.current--;
    };

    updateCount();
    const timer = setInterval(() => {
      updateCount();
    }, 1000);
  };

  const reset = () => {
    setCount(total);
    countRef.current = total;
  };

  return {
    count,
    start,
    isRunning,
  };
}

// 使用示例
function SmsButton() {
  const { count, start, isRunning } = useCountDown({
    total: 6,
    onEnd: () => console.log("可以重新发送了"),
  });

  return (
    <button disabled={isRunning} onClick={start}>
      {isRunning ? `${count}s 后重试` : "发送验证码"}
    </button>
  );
}

export default function App() {
  return (
    <div className="App">
      <SmsButton />
    </div>
  );
}

演示:

倒计时发送验证码

注意点

  1. 闭包问题,需要使用setCount((count) => count - 1);函数式更新状态,使用ref获取最新count
  2. 计时器需要清理,避免内存泄漏
相关推荐
恋猫de小郭16 小时前
Flutter iOS Deep Link 为什么会突然失效:一系列难以言喻的问题
android·前端·flutter
Full Stack Developme16 小时前
跨站脚本攻击 (XSS) 是什么 设计及工作原理
前端·xss
进击的蛋蛋16 小时前
JS对象拷贝
前端
一心只读圣贤书16 小时前
AI 辅助前端组件文档治理:从 Props 说明到交互示例生成
前端
晴殇i17 小时前
最近在 Github 名字叫“马尾辫”,这个真的很有趣看到头像
前端·后端·开源
10mAh17 小时前
【PaddleOCR】扫描版 PDF 无法复制、RAG 检索为空怎么解决?——OCR 解析与版面还原实战
前端·pdf·ocr
IMPYLH17 小时前
HTML 的 <embed> 元素
前端·数据库·html
IT_陈寒17 小时前
Vite打包时静态资源404?加个斜杠就能解决
前端·人工智能·后端
沐土Arvin17 小时前
音频录制sdk开发
前端·微信
anyup17 小时前
【2026年8月】uView Pro 千星,还拿到了 GVP
前端·uni-app·github