在回调中使用 this.setState [英] Using this.setState in a callback
本文介绍了在回调中使用 this.setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码在反应组件中获取 Twitter 时间线:
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})
});
}
但我无法在那里设置 state
,因为 this
未设置为该回调函数中的组件.
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?
n.b.console.log(data) 而不是 this.setState 工作正常,这就是为什么我怀疑问题出在 this 变量上.
推荐答案
你可以这样设置 this
和 .bind
方法,并调用 twitter.get
在 componentDidMount
就像在这个 example
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屋!
查看全文