在回调中使用this.setState [英] Using this.setState in a callback
本文介绍了在回调中使用this.setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码在反应组件中获取推特时间线:
I have the following code getting a twitter timeline in a react component:
componentWillMount: function() {
twitter.get('statuses/user_timeline',
function(error, data) {
this.setState({tweets: data})
});
}
但我无法设置州
那里,因为这个
没有设置为该回调函数中的组件。
But I can't set the state
there, because this
isn't set to the component in that callback function.
如何我可以在回调中设置状态吗?
How can I set the state within that callback?
nb console.log(data)而不是this.setState工作正常,这就是为什么我怀疑这个变量的问题。
推荐答案
您可以使用 .bind
方法设置此
,然后调用 twitter.get
在 示例
You can set this
with .bind
method like this, and call twitter.get
in componentDidMount
as in this example
componentDidMount: function() {
twitter.get('statuses/user_timeline', function(error, data) {
this.setState({tweets: data})
}.bind(this)); // set this that refers to you React component
}
这篇关于在回调中使用this.setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文