猿问

React Hooks:新的状态值未反映在setInterval回调中

我有一个函数react组件,该组件的计数器从10000开始,然后变为0。


我在组件安装期间使用useEffect钩子设置了setInterval回调。回调然后更新计数器状态。


但我不知道为什么,count价值永远不会减少。每次回调运行count为10000。


(我正在使用react&react-dom版本16.8.3)


功能组件如下:


import React, { useState, useEffect, useRef } from 'react'


const Counter = () => {

  const timerID = useRef()

  let [count, setCount] = useState(10000)


  useEffect(() => {

    timerID.current = setInterval(() => {

      //count here is always 10000

      if (count - 1 < 0) {

        setCount(0)

      } else {

        setCount(count - 1)

      }

    }, 1)

  }, [])


  return <h1 className="counter">{count}</h1>

}


export default Counter


慕少森
浏览 273回答 3
3回答

holdtom

您需要注意中的更改count,并清理以下内容useEffect():useEffect(() => {&nbsp; &nbsp; timerID.current = setInterval(() => {&nbsp; &nbsp; &nbsp; if (count - 1 < 0) {&nbsp; &nbsp; &nbsp; &nbsp; setCount(0)&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; setCount(count - 1)&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }, 100)&nbsp; &nbsp; return () => clearInterval(timerID.current);&nbsp; }, [count])正如@Pavel所述,Dan Abramov在这里解释了原因。

青春有我

如您所说的那样,您在安装组件时声明了效果功能。因此,在该范围内,时间值存储内部计数等于10000。这意味着每个时间间隔函数执行都从闭包(10000)中获取计数值。正确地做到这一点实际上很难。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答