我有一个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满意?
答案 0 :(得分:6)
您需要绑定setTimeout
中的函数:
componentDidUpdate: function () {
if (!this.timeoutId) {
this.timeoutId = window.setTimeout(function () {
this.checkYourself();
}.bind(this), UPDATE_CHECK_INTERVAL);
}
},
this.checkYourself()
现在应按预期调用该组件。
答案 1 :(得分:0)
从版本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
答案 2 :(得分:0)
您还可以使用箭头功能来实现此目的:
this.timeoutId = setTimeout(() => {
this.checkYourself();
}, UPDATE_CHECK_INTERVAL);
使用react v0.14.6