javascript - 尝试在我的 React 项目中设置状态时无法读取未定义的属性 setState

标签 javascript reactjs

我尝试从 API 获取数据并通过 setState 方法将其设置为状态,但收到错误:

TypeError: Cannot read property 'setState' of undefined at 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)我获取了所有数据,那么为什么在设置状态时它会给我错误?

最佳答案

有两种解决方案,

将 getDetails 函数定义更改为箭头函数语法

getDetails = () =>  {
  ... all the above code
}    

或者在构造函数中,将其绑定(bind)到 getDetails 函数

this.getDetails = this.getDetails.bind(this);

关于javascript - 尝试在我的 React 项目中设置状态时无法读取未定义的属性 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60091497/

相关文章:

javascript - React JS scrollIntoView() 不会一直向下滚动

javascript - React 句柄更改功能无需参数事件即可工作

python - CentOS Apache服务器无法正确部署Dash 1.4.0,网页一直处于上传状态,为什么?

php - 基于 token 的身份验证中的 session

javascript - 在默认的 Firefox Webconsole 中打开响应并再次发送

javascript - 如果背景图像 url 是 404 那么 jquery

javascript - 创建可重用的 JS 文件 - 导入 - 导出不起作用

javascript - C#中最短的空检查

javascript - 访问多个参数

reactjs - 请向我解释一下这个奇怪的 React 语法