我正在从事番茄时钟项目,我想知道如何使 setInterval 方法在 React 中工作。
我有一个类似这样的代码:
class Pomodoro extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 25,
};
this.handleStartStop = this.handleStartStop.bind(this);
}
handleStartStop() {
let counter = setInterval(timer, 1000);
this.state.count *= 60;
function timer() {
this.setState({
count: (this.state.count -= 1),
});
}
}
render() {
return (
<div>
<div>
<p id="timer-label"> Session</p>
<p id="time-left">{this.state.count}</p>
</div>
<button id="start_stop" onClick={this.handleStartStop}>
Start/Stop
</button>
</div>
);
}
}
我想要发生的是,当我单击开始/停止按钮时。 {this.state.count} 将减 1,但我不知道如何在处理事件时使用 setInterval。
感谢每一条评论和建议。
最佳答案
您可以使用箭头函数以便在计时器回调中获得正确的 this
:
handleStartStop() {
if (this.timer) {
this.timer = clearInterval(this.timer);
return null;
}
this.timer = setInterval(() => this.setState(prevState =>
if (prevState.count === 0) {
this.timer = clearInterval(this.timer);
return null;
}
return {
count: prevState.count - 1,
};
), 1000);
}
另请注意,根据 state
进行更新时,您应始终使用接受第一个参数为先前状态的函数的 setState()
版本。这是因为 setState() 是异步的,并且 React 可能会批量调用它。因此,在调用 setState()
时,您不能依赖当前的 state
。
另外,不要忘记在组件卸载时清除计时器:
componentWillUnmount() {
clearInterval(this.timer);
}
否则,您的回调将在组件卸载后尝试更新状态,这将导致难看的警告。
关于javascript - 如何使用react中的setInterval方法来处理react中的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51704717/