未在reactJs的函数内部定义“ this”

时间:2018-09-16 13:49:22

标签: reactjs

  

我是reactjs的初学者,我正在尝试在api中设置材料   响应,但“此”变得不确定,所以我不能打电话   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)}  />
          )
       }

1 个答案:

答案 0 :(得分:0)

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

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

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

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
    });
}