我想通过点击一个按钮开始一个interval
。
interval
在这里开始,但是我无法访问 counter
的值。因为当计数器等于 5 时,间隔应该停止。
例子如下:
let interval = null;
const stateReducer = (state, value) => value;
function App(props) {
const [counter, setCounter] = useReducer(stateReducer, 0);
const increment = () => {
interval = setInterval(() => {
setCounter(counter + 1);
if (counter === 5) clearInterval(interval);
console.log(counter);
}, 1000);
};
return (
<div>
<p>{counter}</p>
<button className="App" onClick={increment}>
Increment
</button>
</div>
);
}
您可以在 codesandbox 上运行此代码
最佳答案
- 将
const stateReducer = (state, value) => value;
更改为const stateReducer = (state, value) => state+value;
- 在函数外创建一个变量
let current_counter = 0;
- 像这样改变你的增量函数
current_counter = counter;
const increment = () => {
interval = setInterval(() => {
setCounter(1);
if (current_counter === 5) clearInterval(interval);
console.log(current_counter);
}, 1000);
};
完成
关于javascript - 更新后无法访问计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508685/