javascript - 尝试在我的 React 项目中设置状态时无法读取未定义的属性 setState
问题描述
我正在尝试从 API 获取数据并通过该setState
方法将其设置为状态,但出现错误:
TypeError:无法读取 products.jsx:263 处未定义的属性“setState”
代码是:
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)
我是否获得了所有数据,那么为什么在设置状态时它会给我错误?
解决方案
有两种解决方案,
将您的 getDetails 函数定义更改为箭头函数语法
getDetails = () => {
... all the above code
}
或在构造函数中,将此绑定到 getDetails 函数
this.getDetails = this.getDetails.bind(this);
推荐阅读
- google-cloud-platform - 在谷歌云平台创建 API 网关时抛出无法访问的错误
- linux - 在云中的 Heroku 上运行 Elixir 程序
- docusignapi - DocuSign webhook -HMAC 验证
- laravel - Laravel Sanctum 和外部 SPA 返回 401 错误
- liquid-xml - Visual Studio 的自定义转换组件模板
- visual-studio-code - VS 代码 ssh 连接
- python - 如何根据 numpy 中向量的重新排序来重新排序 2D 矩阵轴
- javascript - Discord JS bot 如何从 API 获取递归异步函数
- react-native - 您可以使用钥匙串限制 React Native 中生物识别提示的尝试次数吗?
- erlang - 通过将参数传递给 erl -config 使 sys.config 文件动态化
[参数]