无法通过Promise的then函数设置State

时间:2016-04-18 12:23:03

标签: javascript reactjs

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

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);
}

现在也不行。同样的错误。

4 个答案:

答案 0 :(得分:27)

这是因为this的范围限定,所以当您尝试使用Function.prototype.bind时,您需要处理某些事情。你的错误是你不会一直绑定到最后一个匿名函数。您可能想要做的是一直使用箭头功能,如下所示:

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

箭头函数始终保持this

的上下文

答案 1 :(得分:9)

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

现在,它是固定的。

componentDidMount(){

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

    const response = responseText.json();

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

  }.bind(this));

}

答案 2 :(得分:3)

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

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

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

答案 3 :(得分:0)

您还有错误的setState方法,它的外观应类似于setState({name:'string'})