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. 计时器需要清理,避免内存泄漏
相关推荐
ji_shuke1 小时前
远程排查 Web 系统问题:如何导出 HAR 文件协助定位
前端·问题排查
程序员爱钓鱼2 小时前
Rust String 与 &str 详解:字符串所有权、借用与转换
前端·后端·rust
码农学院2 小时前
GEO与SEO协同:从传统搜索到生成式搜索的平滑迁移路径
服务器·前端·python
To_OC9 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
咩咩啃树皮10 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
阳光是sunny10 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
触底反弹10 小时前
一文搞懂 Tailwind CSS 弹性布局:从原理到实战
前端·css·html
阳光是sunny10 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端
To_OC11 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn11 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js