componentDidMount()中的clearTimeout

时间:2018-08-28 19:15:36

标签: reactjs

每次用户等待响应时,我都试图设置超时时间。 如果用户单击,则应清除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
    )
}

}

2 个答案:

答案 0 :(得分:1)

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

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

userFailedInTime() {
  this.state.userTimeout = setTimeout(() => {
    this.setState({
      catched: "",
      active: getRandom(),
      computerScore:   this.state.computerScore + 1
    });
  }, this.state.delay);
}

然后使用

清除它
clearTimeout(this.state.userTimeout)

答案 1 :(得分:0)

您遇到的问题是,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方法。