在React中Promise中的setState [英] setState inside Promise in React
本文介绍了在React中Promise中的setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的React代码中有一个定义如下的函数:
I have a function in my React code defined like this:
getAttachment(url) {
fetch(url).then((responseText) => {
var response = responseText.json();
response.then(function(response){
this.setState({ attachment: response });
});
}.bind(this));
}
但是编译时出现错误,说我在 .bind(this)
处有一个意外的标记.有什么想法,如何在诺言中设置状态?
But I get an error when this compiles, saying that I have an unexpected token at the .bind(this)
. Any ideas, how to set state inside a promise?
推荐答案
除了绑定 this
,您还可以将引用范围限定在 this
上.喜欢
Instead of binding this
you could just scope the reference to this
. like
var that = this;
,然后引用 that.setState
.
这篇关于在React中Promise中的setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文