【问题标题】:Cannot read property setState of undefined while trying to set the state in my React project尝试在我的 React 项目中设置状态时无法读取未定义的属性 setState
【发布时间】:2020-05-22 07:04:03
【问题描述】:

我正在尝试从 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)我正在获取所有数据,那么为什么在设置状态时它会给我错误?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

传递forEach 第二个参数this。 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)。

relatedsub.forEach(function(item, index) { //... }, **this**);

【讨论】:

    【解决方案2】:

    对此有两种解决方案,

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

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

    在构造函数中,将 this 绑定到 getDetails 函数

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-09
      • 2018-12-05
      • 2016-03-03
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      • 2022-11-17
      • 2019-08-27
      相关资源
      最近更新 更多