reactjs - “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)} />
)
}
解决方案
您应该将构造函数中的函数绑定到组件到 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
});
}
推荐阅读
- html - y 代码不会突出显示代码的 paperscript 部分...它包括 html.plist 而不是 html.json
- python - 使用 python-ldap 在 LDAP 中查询 userCertificate 属性
- c - C中strcpy函数后的变量值变化
- javascript - 尝试创建新的反应原生项目时出错
- powerquery - 将表中的所有数据组合成一个大列?
- postgresql - 列中的空值违反非空约束PostgreSQL
- cmd - Eclipse Foundation 命令行导入引发错误
- sas - 在 SAS 中跟踪失败的作业
- bash - 每半小时安排一次从晚上 10 点到凌晨 1 点的 cron
- javascript - Javascript:如何捕获在 video.play() 中加载视频的错误?