Reactjs 什么';设置状态时,是什么导致了此打字错误?
我正在尝试使用fetch从api获取数据。控制台日志为我提供了正确的json,但在尝试设置状态时出现以下错误: TypeError:无法读取未定义(…)的属性“setState”Reactjs 什么';设置状态时,是什么导致了此打字错误?,reactjs,react-native,fetch,Reactjs,React Native,Fetch,我正在尝试使用fetch从api获取数据。控制台日志为我提供了正确的json,但在尝试设置状态时出现以下错误: TypeError:无法读取未定义(…)的属性“setState” 看起来对“this”的引用不再指向正确的位置,请尝试执行以下操作: fetchFaqs() { var self = this; fetch(FAQ_API) .then(function(response){ return response.json();
看起来对“this”的引用不再指向正确的位置,请尝试执行以下操作:
fetchFaqs() {
var self = this;
fetch(FAQ_API)
.then(function(response){
return response.json();
})
.then(function(json){
console.log("faqs: " , json);
self.setState({
faqs: json,
});
})
.catch((error) => {
console.warn(error);
});
}
如果不想创建自变量,还可以将promise返回函数重构为es6 fat arrow函数,这将把它放在正确的范围内:
fetchFaqs() {
fetch(FAQ_API)
.then((response) => {
return response.json();
})
.then((json) => {
this.setState({
faqs: json,
});
})
.catch((error) => {
console.warn(error);
});
}
fetchFaqs() {
fetch(FAQ_API)
.then((response) => {
return response.json();
})
.then((json) => {
this.setState({
faqs: json,
});
})
.catch((error) => {
console.warn(error);
});
}