// 自定义Hooks逻辑复用 ---倒计时
import { useEffect, useRef, useState } from 'react'
// useCountDown(倒计时的总时间, 倒计时结束执行的操作)
export default function useCountDown (initCount = 10, callBack = () => {}) {
const timeId = useRef<{ id: number }>({ id: 0 })
const [count, setCount] = useState(initCount)
const start = () => {
setCount(initCount)
timeId.current.id = window.setInterval(() => {
setCount((count) => count - 1)
}, 1000)
}
useEffect(() => {
return () => {
// console.log('..........')
clearInterval(timeId.current.id)
}
}, [])
useEffect(
() => {
// console.log(count, timeId.current)
if (count === 0) {
clearInterval(timeId.current.id)
callBack()
}
},
[count]
)
// count:倒计时10-9-8-7...-0 ,start:从哪开始
return { count, start }
}
使用
// 控制按钮是否可以发送验证码
const [sendable, setsendable] = useState(true)
// 调用自定义hooks-倒计时 设置60min后按钮启用setsendable(true)
const { count, start } = useCountDown(60, () => setsendable(true))
添加TypeScrept