倒计时的逻辑复用,抽取相同的业务逻辑,应用场景: 发送短信,倒计时,几秒后跳转网页等等
import { useEffect, useRef, useState } from 'react'
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]
)
return { count, start }
}