在回调中使用this.setState

san*_*zer 3 javascript callback this reactjs

我有以下代码在react组件中获取twitter时间轴:

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

但我无法设置state那里,因为this没有设置回该函数中的组件.

如何在回调中设置状态?

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

Ale*_* T. 6

您可以设置this.bind这样的方法,并呼吁twitter.getcomponentDidMount如本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
}
Run Code Online (Sandbox Code Playgroud)

Example