【问题标题】:Couldn't setState from the then function of the Promise无法从 Promise 的 then 函数中设置状态
【发布时间】:2016-04-18 12:23:02
【问题描述】:

我正在尝试从使用fetch 函数收到的promise 更新状态。

componentDidMount(){

fetch(url).then((responseText) => {

     var response = responseText.json();

     response.then(function(response){
         this.setState(response);
     });

  });
}

我收到setState 不是函数的错误

然后,我尝试通过bind(this) 传递this 值,如下所示。

componentDidMount(){

fetch(url).then((responseText) => {

     var response = responseText.json();

     response.then(function(response){
         this.setState(response);
     });

  }).bind(this);
}

它现在也不起作用。又是同样的错误。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    抱歉,刚才发现我没有正确绑定this变量。

    现在,它已修复。

    componentDidMount(){
    
      fetch(url).then((responseText) => {
    
        const response = responseText.json();
    
        response.then(function(response){
            this.setState(response);
        });
    
      }.bind(this));
    
    }
    

    【讨论】:

      【解决方案2】:

      这是因为this 的作用域,所以当您尝试使用Function.prototype.bind 时,您会遇到一些问题。您的错误是您没有一直绑定到最后一个匿名函数。您可能想要做的是一直使用箭头函数,如下所示:

      componentDidMount(){
          fetch(url)
              .then((responseText) => responseText.json())
              .then((response) => this.setState(response));
      }
      

      箭头函数始终保持this 的上下文。

      【讨论】:

        【解决方案3】:

        您的第二个承诺没有当前的this 上下文。您也可以在这里使用箭头函数。

        componentDidMount(){
          fetch(url).then((responseText) => {
             return responseText.json();
          })
          .then((response) => {
             this.setState(response);
          });
        }
        

        此外,链接而不是嵌套你的 Promise 将有助于提高可读性,并可能帮助你避免 callback hell

        【讨论】:

          【解决方案4】:

          你也有错误的方法来设置状态它应该看起来像 setState({name : 'string'})

          【讨论】:

            猜你喜欢
            • 2021-01-02
            • 1970-01-01
            • 1970-01-01
            • 2021-12-04
            • 2020-06-02
            • 2021-12-02
            • 2015-02-20
            • 1970-01-01
            • 2021-02-12
            相关资源
            最近更新 更多