useCountDown
返回分钟倒计时的 React 状态钩子。
useCountDown 接受以秒为单位的持续时间,返回一个每秒更新的 [hour, minute, second] 格式化字符串元组。可选的 format 函数可自定义字符串格式,可选的 callback 在倒计时结束时被调用。该 hook 自动管理定时器生命周期,在卸载时清理。
使用场景
- 显示促销活动、事件或限时优惠的倒计时定时器
- 构建在时间到期时触发操作的考试或测验定时器
- 显示距计划事件(例如午夜、发布日期)的剩余时间
注意事项
- SSR 兼容性:在服务端渲染时,确保初始
time值在服务端和客户端计算一致,以避免水合不匹配。示例中使用suppressHydrationWarning就是出于此原因。 - 自定义格式:默认格式产生
HH:MM:SS字符串。传入自定义format函数更改输出(例如补零、本地化标签)。 - 完成回调:可选的第三个参数在倒计时到零时触发一次,适用于重定向、提醒或状态转换。
Usage
Live Editor
function Demo() { const now = new Date(); const tomorrow = new Date(); tomorrow.setDate(now.getDate() + 1); tomorrow.setHours(0, 0, 0, 0); const diffInSec = Math.floor((tomorrow.getTime() - now.getTime()) / 1000); // 如果您的应用在服务器端运行,必须传递与客户端相同的时间 // 这个 demo 没有在服务器端运行 const [hour, minute, second] = useCountDown(diffInSec); return ( <div suppressHydrationWarning={true}>{`${hour}:${minute}:${second}`}</div> ); };
Result
API
useCountdown
Returns
readonly [string, string, string]: 包含以下元素的元组:
- 小时。
- 分钟。
- 秒数。
Arguments
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| time | 时间差 | number (必填) | - |
| format | 时间格式化函数 | ((num: number) => [string, string, string]) | undefined | HH MM SS |
| callback | 倒计时结束的回调函数 | (() => void) | undefined | - |