菜单

useCooldown()

组件背后的 hook。可以直接用它构建自己的界面,或在页面的多个部分之间共享同一个冷却。

import { useCooldown } from 'input-cooldown'

const cd = useCooldown({
  storageKey: `otp:${email}`,
  duration: [30, 60, 120],
  maxAttempts: 5,
  onResend: () => api.resend(email),
})

<button onClick={cd.trigger} aria-disabled={!cd.canResend}>
  {cd.status === 'counting' ? `${cd.remaining} 秒后重发` : '重新发送'}
</button>

选项

属性类型默认值
storageKey
持久化与同步的键,必填。不能叫 `key`,因为 React 保留了它。
string—
duration
秒数。数组表示按尝试次数递增的退避序列,最后一个值会重复使用。
number | number[]30
maxAttempts
最多发送次数。达到后状态变为 exhausted。
number—
onResend
发送验证码。返回 { retryAfter } 或 { endsAt } 可覆盖时长;抛出错误则进入 error 状态。
() => void | ResendResult | Promise<…>—
autoStart
如果没有已保存的状态,挂载时就开始计时。适用于刚发送完验证码就打开的页面。
booleanfalse
expiresAfter
冷却结束后多少秒忘记已尝试次数。
number900
storage
状态存放的位置。参见“核心与存储”。
StorageAdapterlocalStorage
onReady
当此 store 观察到的倒计时进入 ready 时调用。
() => void—
onError
当 onResend 抛出错误时调用。
(error: unknown) => void—
now
替换时钟,用于测试。
() => numberDate.now

返回值

属性类型默认值
status
当前状态。
'hydrating' | 'idle' | 'loading' | 'counting' | 'ready' | 'error' | 'exhausted'—
remaining
剩余整秒数(向上取整)。未计时时为 0。
number—
canResend
在 idle、ready 和 error 状态下为 true。
boolean—
attempt
目前已发送的次数。
number—
attemptsLeft
未设置 maxAttempts 时为 null。
number | null—
startedAt / endsAt
毫秒级时间戳。可用于平滑的进度动画。
number | null—
error
在 error 状态下,onResend 抛出的内容。
unknown—
trigger()
调用 onResend,然后开始冷却。canResend 为 false 时忽略。resolve 的值表示是否已发送。
() => Promise<boolean>—
start(opts?)
不调用 onResend,直接开始冷却。
({ retryAfter?, endsAt?, countAttempt? }) => void—
reset()
清除这个键的所有状态。
() => void—

更换键

当 storageKey 或 storage 变化时,hook 会切换到对应冷却的状态。其他选项每次渲染都会重新读取,不会重置任何东西。

useCooldown() | input-cooldown