设置状态时导致此 TypeError 的原因是什么?
What's causing this TypeError when setting state?
我正在尝试使用 fetch 从 api 获取数据。控制台日志为我提供了正确的 json,但在尝试设置状态时出现以下错误:
TypeError: 无法读取 属性 'setState' of undefined(…)
getInitialState() {
return {
checklist: {},
documents: [],
questions: [],
faqs: [],
hospitals: [],
profile: {},
guarantor: {},
}
},
componentDidMount(){
this.fetchUser(1);
this.fetchFaqs();
},
fetchFaqs() {
fetch(FAQ_API)
.then(function(response){
return response.json();
})
.then(function(json){
console.log("faqs: " , json);
this.setState({
faqs: json,
});
})
.catch((error) => {
console.warn(error);
});
},
似乎对 '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);
});
}
如果你不想创建 self 变量,你也可以将你的承诺 return 函数重构为 es6 胖箭头函数,这会将它放在正确的范围内:
fetchFaqs() {
fetch(FAQ_API)
.then((response) => {
return response.json();
})
.then((json) => {
this.setState({
faqs: json,
});
})
.catch((error) => {
console.warn(error);
});
}
我正在尝试使用 fetch 从 api 获取数据。控制台日志为我提供了正确的 json,但在尝试设置状态时出现以下错误:
TypeError: 无法读取 属性 'setState' of undefined(…)
getInitialState() {
return {
checklist: {},
documents: [],
questions: [],
faqs: [],
hospitals: [],
profile: {},
guarantor: {},
}
},
componentDidMount(){
this.fetchUser(1);
this.fetchFaqs();
},
fetchFaqs() {
fetch(FAQ_API)
.then(function(response){
return response.json();
})
.then(function(json){
console.log("faqs: " , json);
this.setState({
faqs: json,
});
})
.catch((error) => {
console.warn(error);
});
},
似乎对 '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);
});
}
如果你不想创建 self 变量,你也可以将你的承诺 return 函数重构为 es6 胖箭头函数,这会将它放在正确的范围内:
fetchFaqs() {
fetch(FAQ_API)
.then((response) => {
return response.json();
})
.then((json) => {
this.setState({
faqs: json,
});
})
.catch((error) => {
console.warn(error);
});
}