gpt4 book ai didi

javascript - 无法从 Promise 的 then 函数设置状态

转载 作者:行者123 更新时间:2023-12-03 13:07:47 24 4
gpt4 key购买 nike

我正在尝试使用 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);
}

现在也不起作用了。再次出现同样的错误。

最佳答案

这是因为 this 的作用域,因此当您尝试使用 Function.prototype.bind 时,您就会发现一些东西。你的错误是你没有一直绑定(bind)到最后一个匿名函数。您可能想要做的是一直使用箭头函数,如下所示:

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

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

关于javascript - 无法从 Promise 的 then 函数设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36693898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com