尽管有相反的警告,React 仍未绑定函数调用

React is not binding function call despite warnings to the contrary

我有一个 React 组件需要 运行 检查 setTimeout() 调用。以下是我的方法调用

componentDidUpdate: function () {
    // Despite console warnings, React does *not* do this.
    var boundCheck = this.checkYourself.bind(this);
    if (!this.timeoutId) {
        this.timeoutId = window.setTimeout(function () {
            boundCheck();
        }, UPDATE_CHECK_INTERVAL);
    }
},

这将在控制台上产生以下警告:

bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call.

但是,如果我将方法更改为以下内容:

componentDidUpdate: function () {
    if (!this.timeoutId) {
        this.timeoutId = window.setTimeout(function () {
            this.checkYourself();
        }, UPDATE_CHECK_INTERVAL);
    }
},

我得到一个异常,因为 this 指的是 window。有没有办法让 React 开心?

您需要绑定setTimeout中的函数:

componentDidUpdate: function () {
  if (!this.timeoutId) {
    this.timeoutId = window.setTimeout(function () {
      this.checkYourself();
    }.bind(this), UPDATE_CHECK_INTERVAL);
  }
},

this.checkYourself() 现在应该按预期调用组件。

从 0.4 版本开始,React 自动绑定你在 createClass 中创建的所有方法并将其绑定到正确的上下文,你只需要在 createclass 中声明一个方法并直接调用 setTimeout(this.method, 1000)

https://facebook.github.io/react/blog/2013/07/02/react-v0-4-autobind-by-default.html

你也可以使用箭头函数来实现:

this.timeoutId = setTimeout(() => {
    this.checkYourself();
}, UPDATE_CHECK_INTERVAL);

用反应测试 v0.14.6