无法从Promise的then函数setState

Sri*_*man 18 javascript reactjs

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

componentDidMount(){

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

     var response = responseText.json();

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

  });
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误setState不是函数

然后,我试图bind(this)传递this如下的值.

componentDidMount(){

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

     var response = responseText.json();

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

  }).bind(this);
}
Run Code Online (Sandbox Code Playgroud)

它现在也没有用.同样的错误.

Nic*_*ren 36

这是因为它的范围this很广,所以当你尝试使用时,你就会有所作为Function.prototype.bind.你的错误是你没有一直绑定到最后一个匿名函数.您可能想要做的是一直使用箭头函数,如下所示:

componentDidMount(){
    fetch(url)
        .then((responseText) => responseText.json())
        .then((response) => this.setState(response));
}
Run Code Online (Sandbox Code Playgroud)

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


Sri*_*man 11

对不起,刚才发现我没有this正确绑定变量.

现在,它是固定的.

componentDidMount(){

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

    const response = responseText.json();

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

  }.bind(this));

}
Run Code Online (Sandbox Code Playgroud)