定义React的Ts定时器Hooks组件

452 阅读1分钟

封装倒计时装置,可用于验证码之类

代码

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 }
}


用法

1.导入这个Hooks函数

import useCountDown from '@/hooks/useCountDown'

2.再将这个函数结构出来 start为开始计时的方法, count是用来显示当前秒数, useCountDown(Number) 这里number为自己定义的时间

const { start, count } = useCountDown(10)

3.举个例子 点击事件中 启动倒计时

onClick={start()}

就能看到实时获取的值了

<p> {count} </p>