我尝试在每次等待用户的反应时设置超时。如果用户单击,则应清除setTimeout。因此,我尝试获取setTimeout的ID,以便能够在clearTimeout(ID)中使用它。获取ID的第一种方法是调用userFailedInTime(),我还有一点computerScore。第二种方式在我看来是行不通的。
请问,如何正确清除超时?
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
)
}}
发布于 2018-08-29 03:19:45
每次调用userFailedInTime时,都会创建一个新的超时。这里重要的部分是它是一个新的超时,即使你多次调用它,你也不会得到相同的超时。这意味着您没有清除您正在设置的超时。
而是将超时存储在状态中或存储为类变量
userFailedInTime() {
this.state.userTimeout = setTimeout(() => {
this.setState({
catched: "",
active: getRandom(),
computerScore: this.state.computerScore + 1
});
}, this.state.delay);
}然后用以下命令清除它
clearTimeout(this.state.userTimeout)发布于 2018-08-29 03:20:44
您的方法中的问题是failID没有更新。您需要在调用userFailedInTime方法时更新它
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.failID = this.userFailedInTime()
}
}在第二种情况下
clearTimeout(this.userFailedInTime());
this.userFailedInTime()您将执行两次userFailedInTime方法,一次是使用返回值清除setTimeout,而不是下一次。
https://stackoverflow.com/questions/52064838
复制相似问题