自定义Hook之定时器-TypeScript版

370 阅读1分钟
//ts版
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 }
}
// js版
import { useState, useEffect, useRef } from 'react'

export const useCountDown = (callback = () => { }) => {
    var timeRef = useRef(null)
    const [flag, setFlag] = useState(true)
    const [timeText, setTimeText] = useState('获取验证码')
    const [count, setCount] = useState('0')
    useEffect(() => {
        return () => {
            clearInterval(timeRef.current)
        }
    }, [])
    useEffect(() => {
        if (count === 0) {
            clearInterval(timeRef.current)
            setTimeText('获取验证码')
            setFlag(true)
            callback()
        } else {
            setTimeText(count + 's 后重新获取')
        }
        if (+count === 0) setTimeText('获取验证码')

    }, [count, callback])
    const start = () => {
        if (!flag) return
        setFlag(false)
        timeRef.current = setInterval(() => {
            setCount((count) => count - 1)
        }, 1000)
    }

    return { flag, timeText, count, start, setCount }
}

// 倒计时 Hook 使用说明
// flag 为是否以开始定时器  开始为false 未开始为true
// timeText 为按钮的文本
// count 为秒数
// start 为开始的函数
// setCount 为设置倒计时开始数字
// callback 为回调函数