setInterval 中使用React hooks的 state 值不变的解决办法


需求:做一个倒计时按钮,在“发送验证码”后开始60的倒数计时。

使用 React hooks 的形式:

  // 倒计时按钮状态
  const [loading, setLoading] = useState(false)
  const [count, setCount] = useState(60)

  useEffect(() => {
    if (loading) {
      const btnClock = setInterval(() => {
        if (count < 1) {
          setLoading(false)
          setCount(60)
          clearInterval(btnClock)
        }
        setCount(prevCount => prevCount - 1)
      }, 1000)
    }
  }, [loading])

问题:

判断 if (count < 1) 中的count 因为某种原因成了闭包(原因我很疑惑?),每次更新时,并不会从60 - 59 - 58。。。而是始终保持60。这样的话倒计时永不会结束。

解决:

使用 useRef hook 存储每次count的变化值,再在 setInterval 中引用 countRef.current

  // 倒计时按钮状态
  const [loading, setLoading] = useState(false)
  const [count, setCount] = useState(60)

  const countRef = useRef(count)

  useEffect(() => {
    countRef.current = count
  }, [count])

  useEffect(() => {
    if (loading) {
      const btnClock = setInterval(() => {
        if (countRef.current < 1) {
          setLoading(false)
          setCount(60)
          clearInterval(btnClock)
        }
        setCount(prevCount => prevCount - 1)
      }, 1000)
    }
  }, [loading])

说明:

useEffect hook 也是顺序执行,为 countRef 在每次render 时更新。

方案借鉴自老哥:https://blog.csdn.net/frozen_warrior/article/details/115870501