随笔 - 21,  文章 - 0,  评论 - 0,  阅读 - 7633

需求:做一个倒计时按钮,在“发送验证码”后开始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

posted on   令狐虫虫666  阅读(560)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示