无法从Promise的then函数setState [英] Couldn't setState from the then function of the Promise

查看:784
本文介绍了无法从Promise的then函数setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 fetch 函数从承诺更新状态。

I'm trying to update the state from the promise which I received using the fetch function.

componentDidMount(){

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

     var response = responseText.json();

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

  });
}

我收到的错误是 setState 不是函数

I was getting the error that the setState is not an function

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

Then, I tried to bind(this) to pass the this value like below.

componentDidMount(){

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

     var response = responseText.json();

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

  }).bind(this);
}

现在也不行。再次出现相同的错误。

It is not working now also. Same error again.

推荐答案

这是因为的范围 ,当你尝试使用 Function.prototype.bind 时,你会发现一些事情。你的错误是你没有一直绑定到最后一个匿名函数。您可能想要做的是一直使用箭头函数,如下所示:

This is because of the scoping of this, so you're on to something when you're trying to use Function.prototype.bind. Your mistake is that you don't bind all the way down to the last anonymous function. What you probably want to do is use arrow functions all the way, like this:

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

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

这篇关于无法从Promise的then函数setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆