我正在尝试以这种方式访问setInterval
内部的组件的状态,但是它不起作用:
componentDidMount: function() {
setInterval(function() {
console.log(this.state);
}, 3000);
}
但是,如果我将回调函数放在单独的组件方法中,则可以完美地工作:
displayState: function() {
console.log(this.state)
}
componentDidMount: function() {
setInterval(this.displayState(), 3000);
}
知道为什么会这样吗?我宁愿使用第一个选项。
最佳答案
在您的第一个示例中,当回调函数触发时,this
超出范围。解决此问题的一种方法是使用变量:
componentDidMount: function() {
var self = this;
setInterval(function() {
console.log(self.state);
}, 3000);
}
第二次尝试的问题是您正在立即调用该函数,并将执行该函数的结果传递给
setInterval
。您应该传递函数本身,注意绑定(bind)this
的值:componentDidMount: function() {
setInterval(this.displayState.bind(this), 3000);
}
要澄清的是,此方法与问题中的第二个示例之间的区别在于,此处将一个函数传递给
setInterval
(因为function.bind()
返回一个函数)。当您使用
React.createClass
时,由于autobind,因此无需自己管理this
的绑定(bind)。这意味着您可以只传递函数本身,this
将与原始上下文中的相同:componentDidMount: function() {
setInterval(this.displayState, 3000);
}
当然,最合适的方法取决于您是否愿意使用匿名函数。
关于javascript - 在React.js中的setInterval内部发布访问状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26348557/