我正在尝试从API提取数据并通过setState
方法将其设置为状态,但是出现错误:
TypeError:无法读取未定义的属性'setState' 在products.jsx:263
代码是:
getDetails () {
var subjectfinal = [];
let relatedsub = JSON.parse(subjects.related_subjects);
relatedsub.forEach(function(item, index) {
let formData = new FormData();
formData.append("subject_id", item.value);
fetch("https://***********/get_subject", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(responseJson => {
subjectfinal.push(responseJson[0])
console.log(subjectfinal) //gives me the subject data i,e array contaning 3 objects in it
this.setState({ subjectstobedisplayed: subjectfinal }),()=>console.log(this.state.subjectstobedisplayed)) // gives error
)
})
.catch(error => {
swal("Warning!", "Check your network!", "warning");
console.log(error);
});
});
};
我想问问console.log(subjectfinal)
是否正在获取所有数据,然后为什么在设置状态时却给我错误?
答案 0 :(得分:0)
有两种解决方案,
将getDetails函数定义更改为箭头函数语法
getDetails = () => {
... all the above code
}
在构造函数中或,将其绑定到getDetails函数
this.getDetails = this.getDetails.bind(this);
答案 1 :(得分:0)
传递forEach第二个参数this
。 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)。
relatedsub.forEach(function(item, index) { //... }, **this**);