我有一个函数 React 组件,它有一个从 10000 开始到 0 的计数器。
我在组件安装期间使用 useEffect Hook 设置一个 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
这是 codesandbox 的链接:link
最佳答案
您需要观察 count
的变化,并清理您的 useEffect()
:
useEffect(() => {
timerID.current = setInterval(() => {
if (count - 1 < 0) {
setCount(0)
} else {
setCount(count - 1)
}
}, 100)
return () => clearInterval(timerID.current);
}, [count])
正如@Pavel 提到的,Dan Abramov 解释了为什么 here .
关于javascript - react Hook : new state value not reflecting in setInterval callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55563287/