Reactjs componentDidMount()中的clearTimeout
我试图在每次等待用户反应时设置超时。 如果用户单击,则应清除setTimeout。 所以,我试图获得setTimeout的ID,以便能够在clearTimeoutID中使用它。 第一种获得ID的方法是envokes UserFailedTime,我的computerScore得分又多了一分。 第二种方法不像我看到的那样有效 请问,如何正确清除超时Reactjs componentDidMount()中的clearTimeout,reactjs,Reactjs,我试图在每次等待用户反应时设置超时。 如果用户单击,则应清除setTimeout。 所以,我试图获得setTimeout的ID,以便能够在clearTimeoutID中使用它。 第一种获得ID的方法是envokes UserFailedTime,我的computerScore得分又多了一分。 第二种方法不像我看到的那样有效 请问,如何正确清除超时 class MyContainer extends React.Component{ state = { computerScore: 0,
class MyContainer extends React.Component{
state = {
computerScore: 0,
}
componentDidMount() {
// The first way to get timeOut ID
this.failID = this.userFailedInTime();
// The second way to get timeOut ID
this.userFailedInTime = this.userFailedInTime.bind(this);
}
userFailedInTime() {
return setTimeout(() => {
this.setState({
catched: "",
active: getRandom(),
computerScore: this.state.computerScore + 1
});
}, this.state.delay);
}
componentDidUpdate(){
if(
// Some conditional
){
// The first way to clear timeout I've tried but it fires userFailedInTime
// in componentDidMount() and sets computerScore 1 point higher which is not what I want
clearTimeout(this.failID);
this.userFailedInTime()
// The second way to clear timeout I've tried seems doesn't work
clearTimeout(this.userFailedInTime());
this.userFailedInTime()
}
}
render(){
return (
// Some code
)
}
}每次调用UserFailedTime时,都会创建一个新的超时。这里重要的一点是,这是一个新的超时,即使您多次调用它,也不会得到相同的超时。这意味着您没有清除正在设置的超时 而是将超时存储在状态中或作为类变量
userFailedInTime() {
this.state.userTimeout = setTimeout(() => {
this.setState({
catched: "",
active: getRandom(),
computerScore: this.state.computerScore + 1
});
}, this.state.delay);
}
然后用你的手把它清理干净
clearTimeout(this.state.userTimeout)
方法中的问题是failID没有更新。调用userFailedInTime方法时需要更新它 在第二种情况下
clearTimeout(this.userFailedInTime());
this.userFailedInTime()
您将执行userFailedInTime方法两次,一次是使用返回值清除setTimeout,而不是下一次
clearTimeout(this.userFailedInTime());
this.userFailedInTime()