首页 > 解决方案 > “this”未在 reactJs 的函数内部定义

问题描述

我是 reactjs 的初学者,我正在尝试在 api 响应中设置材料,但是“this”变得未定义,所以我不能调用 this.setMaterials(materials) 为什么这在 getMaterials() 函数中变得未定义?

   constructor() {
        super();
        this.obj = {
            materials: []
        };
    }
    getMaterials(string) {
        var options = {
            url: 'materials',
            method: 'get',
        };
        http.makeRequest(options).then(res => {
            console.log(this)// undefined
            this.setMaterials(res); //try to set materials in the obj variable
        });
    }

    setMaterials(materials) {
        this.obj.materials = materials;
    }

render(){
    return(
       <IntegrationDownshift  getItems={this.getMaterials.bind(this)}  />
          )
       }

标签: reactjs

解决方案


您应该将构造函数中的函数绑定到组件到 this 或使用新范围,因为您应该定义箭头函数以便将函数自动绑定到组件,例如:

setMaterials = (materials)=> {
  this.obj.materials = materials;
}

因此,您可以从代码中的任何位置调用 this.setMaterials 和 getMaterials 函数:(因此您可以在其中调用 this 而无需手动绑定函数)

getMaterials = (string) => {
    var options = {
        url: 'materials',
        method: 'get',
    };
    http.makeRequest(options).then(res => {
        console.log(this)// undefined
        this.setMaterials(res); //try to set materials in the obj 
         variable
    });
}

推荐阅读