在回调中使用this.setState

时间:2015-12-05 19:00:13

标签: javascript callback reactjs this

我有以下代码在反应组件中获取推特时间线:

  componentWillMount: function() {
    twitter.get('statuses/user_timeline',
    function(error, data) {
      this.setState({tweets: data})
     });
  }

但我无法在那里设置state,因为this未设置为该回调函数中的组件。

如何在回调中设置状态?

n.b。 console.log(data)而不是this.setState工作正常,这就是为什么我怀疑这个变量存在问题。

3 个答案:

答案 0 :(得分:6)

您可以使用this这样的方法设置.bind,并在componentDidMount中调用twitter.get,如此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
}

Example

答案 1 :(得分:4)

永远不要在componentWillMount中执行ajax调用。

在componentDidMount中执行

还有一个范围问题,因为使用亚历山大建议(绑定)。另一种可能性是:

componentDidMount: function() {
    var self = this;
    twitter.get('statuses/user_timeline', function(error, data) {
        self.setState({tweets: data})
    });
}

此处还有更多细节http://facebook.github.io/react/tips/initial-ajax.html(评论中已经由klimo强调)

答案 2 :(得分:2)

将其置于 componentDidMount 中有两种方法,您可以解决问题:

<强> 1。将此范围绑定到函数

.bind(本)

SCNNode

<强> 2。使用胖箭

=&GT;

twitter.get('statuses/user_timeline', function(error, data) {
   this.setState({tweets: data})
}).bind(this);