【问题标题】:Using this.setState in a callback在回调中使用 this.setState
【发布时间】:2020-11-06 23:38:16
【问题描述】:

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

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

但我不能在那里设置state,因为this 没有设置为该回调函数中的组件。

如何在回调中设置状态?

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

【问题讨论】:

    标签: javascript callback reactjs this


    【解决方案1】:

    您可以像这样使用.bind 方法设置this,并在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
    }
    

    【讨论】:

      【解决方案2】:

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

      在 componentDidMount 中执行

      还有一个范围问题,为此使用 Alexander 建议的(绑定)。另一种可能是:

      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(已在 cmets 中由 klimo 下划线)

      【讨论】:

      • 感谢您的提及,弗朗索瓦。要简短地添加到您的答案中,您可以使用 ES6 粗箭头来避免绑定或完全使用 self = this(error, data) => { ...(您需要像 Babel 这样的转译器)。
      • componentDidMount 对我来说似乎根本没有开火。我的代码:getInitialState: function(){ return({tweets: 'getInitialState'}) } , componentDidMount: function() { twitter.get('statuses/user_timeline', function(error, data) { this.setState({tweets: 'callback'}) console.log('callback') }.bind(this)); this.setState({tweets:'componentDidMount'}) console.log('componentDidMount') } 呈现“getInitialState”
      • 把代码放在你的问题中,这样读起来会伤害我的眼睛
      【解决方案3】:

      把它放在componentDidMount里面有两种方法,你可以解决这个问题:

      1.将此作用域绑定到函数

      .bind(这个)

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

      2。使用粗箭头

      =>

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-23
        • 1970-01-01
        • 2019-02-14
        • 1970-01-01
        • 2019-09-08
        • 2019-04-23
        • 1970-01-01
        • 2020-04-12
        相关资源
        最近更新 更多