首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >componentDidMount()中的clearTimeout

componentDidMount()中的clearTimeout
EN

Stack Overflow用户
提问于 2018-08-29 03:15:36
回答 2查看 126关注 0票数 0

我尝试在每次等待用户的反应时设置超时。如果用户单击,则应清除setTimeout。因此,我尝试获取setTimeout的ID,以便能够在clearTimeout(ID)中使用它。获取ID的第一种方法是调用userFailedInTime(),我还有一点computerScore。第二种方式在我看来是行不通的。

请问,如何正确清除超时?

代码语言:javascript
复制
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
    )
}

}

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-29 03:19:45

每次调用userFailedInTime时,都会创建一个新的超时。这里重要的部分是它是一个新的超时,即使你多次调用它,你也不会得到相同的超时。这意味着您没有清除您正在设置的超时。

而是将超时存储在状态中或存储为类变量

代码语言:javascript
复制
userFailedInTime() {
  this.state.userTimeout = setTimeout(() => {
    this.setState({
      catched: "",
      active: getRandom(),
      computerScore:   this.state.computerScore + 1
    });
  }, this.state.delay);
}

然后用以下命令清除它

代码语言:javascript
复制
clearTimeout(this.state.userTimeout)
票数 1
EN

Stack Overflow用户

发布于 2018-08-29 03:20:44

您的方法中的问题是failID没有更新。您需要在调用userFailedInTime方法时更新它

代码语言:javascript
复制
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()
    }

  }

在第二种情况下

代码语言:javascript
复制
 clearTimeout(this.userFailedInTime());
 this.userFailedInTime()

您将执行两次userFailedInTime方法,一次是使用返回值清除setTimeout,而不是下一次。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52064838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档