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

React is not binding function call despite warnings to the contrary

本文关键字:警告 绑定 函数调用 React      更新时间:2023-09-26

我有一个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():您正在将一个组件方法绑定到该组件。React以高性能的方式自动为您执行此操作,因此您可以安全地删除此调用。

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

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 测试