【发布时间】:2019-09-17 01:07:05
【问题描述】:
我正在制作一个简单的进度条,当我使用 setInterval 时,我注意到挂钩状态的奇怪行为。这是我的示例代码:
const {useState} = React;
const Example = ({title}) => {
const [count, setCount] = useState(0);
const [countInterval, setCountInterval] = useState(0)
let intervalID
const handleCount = () => {
setCount(count + 1)
console.log(count)
}
const progress = () => {
intervalID = setInterval(() => {
setCountInterval(countInterval => countInterval + 1)
console.log(countInterval)
if(countInterval > 100) { // this is never reached
setCountInterval(0)
clearInterval(intervalID)
}
},100)
}
const stopInterval = () => {
clearInterval(intervalID)
}
return (
<div>
<p>{title}</p>
<p>You clicked {count} times</p>
<p>setInterval count { countInterval } times</p>
<button onClick={handleCount}>
Click me
</button>
<button onClick={progress}>
Run interval
</button>
<button onClick={stopInterval}>
Stop interval
</button>
</div>
);
};
// Render it
ReactDOM.render(
<Example title="Example using simple hook:" />,
document.getElementById("app")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="app"></div>
如果我通过handleCount 设置状态,一切都会按预期发生,但是当我运行progress 函数时,内部 setInterval countInterval 值不会改变强>在所有。不管怎样,countInterval在状态上发生了变化。
为了解决这个问题,我在 progress 函数中使用了变量,如下所示:
const progress = () => {
let internalValue = 0
intervalID = setInterval(() => {
setCountInterval(internalValue)
internalValue++
if(internalValue > 100) {
setCountInterval(0)
clearInterval(intervalID)
}
},100)
}
这很好用,但我仍然想知道是否有更好的方法以及在第一种情况下我做错了什么。
第二个问题是我无法清除progress 函数之外的间隔,我不确定我在这里做错了什么或者我错过了什么?提前感谢您的任何帮助和建议。
【问题讨论】:
-
我认为你应该使用effect hook 来处理类似的事情。
-
为什么不只是
setCountInterval(countInterval => countInterval > 100 ? 0 : countInterval + 1)? -
@JonasWilms 这很聪明,但我还需要以某种方式清除Interval。
标签: javascript reactjs setinterval react-hooks