【问题标题】:How access object which created interval from interval callback?如何从区间回调中访问创建区间的对象?
【发布时间】:2021-04-27 19:22:57
【问题描述】:

我是 JavaScript 新手,我目前的问题没有提出来。 我在这里有一个 React 应用程序,我尝试通过计时器功能来扩展它。我创建了一个计时器(类似于这个问题:setInterval in a React app)并且计时器功能本身正在工作。

但是计时器回调(或更确切地说是setInterval 回调)不起作用。在setInterval 中,变量this 指向Windows,但我认为它应该指向App,这是创建计时器并包含setInterval 回调的类/对象。因此我得到以下错误。

以下是我所做的关键代码更改:

class App extends Component {

  //...

  componentDidMount() {

    //...

    var intervalId = setInterval(this.timer, 5000);
    // store intervalId in the state so it can be accessed later:
    this.setState({intervalId: intervalId});
  }

  componentWillUnmount() {
    
    //...

    // use intervalId from the state to clear the interval
    clearInterval(this.state.intervalId);
  }

  timer() {
    for (let i = 0; i < this.state.whitelist.length; i++) {
      this.requestDeviceStatus(this.state.whitelist[i]);
    }
  }

 //...

}

但您可以在此处访问完整的源代码/提交: https://github.com/wewa00/Reacticz/blob/backgroundtimer/src/App.js, (这是相关的提交:02e3e936bcabba。)

为什么this 指向Window,我如何从timer() 中访问App

【问题讨论】:

    标签: javascript node.js reactjs npm


    【解决方案1】:

    类型错误

    通过 ES6 箭头方法使用计时器功能。

    timer=()=>{
       for (let i = 0; i < this.state.whitelist.length; i++) {
            this.requestDeviceStatus(this.state.whitelist[i]);
        }
    }
    

    【讨论】:

    • 感谢您的提示。你的回答真的很快。我有一个错误,并像你所说的那样纠正了这一点。但问题仍然存在,正如您在更新后的问题中看到的那样。
    • 检查我更新的答案。为什么我建议=&gt; 而不是绑定。我们不需要记住在构造函数中绑定每个函数。它在构造函数中很拥挤
    • 我不太明白这一点。但是在timer()Scope 中有你的建议this: App
    • this 以类范围为目标。如果您使用time() 就像没有bind(this) 一样@Prime 答案。 this 可能无法正常工作。同样,如果您使用 ES6 方法,如 =&gt; 函数,它将允许父范围 this 在 timer() 函数内
    【解决方案2】:

    你需要在timer函数中使用bind来访问App

    class App extends Component {
    
      //...
    
      componentDidMount() {
    
        //...
    
        var intervalId = setInterval(this.timer, 5000);
        // store intervalId in the state so it can be accessed later:
        this.setState({intervalId: intervalId});
        this.timer = this.timer.bind(this); // <------------------------------
      }
    
      componentWillUnmount() {
        
        //...
    
        // use intervalId from the state to clear the interval
        clearInterval(this.state.intervalId);
      }
    
      timer() {
        for (let i = 0; i < this.state.whitelist.length; i++) {
          this.requestDeviceStatus(this.state.whitelist[i]);
        }
      }
    
     //...
    
    }
    

    【讨论】:

    • 我试过了,但我仍然收到相同的错误消息。当我调试我的应用程序时,我可以看到 this: WindowScopetimer() 中。
    猜你喜欢
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多