![](/img/trans.png)
[英]`this` being undefined on object method when called as a react component prop
[英]Undefined 'this' when handing class method to React component
我的 React 应用程序在 API class 中有 API 个方法:
class API {
constructor() {
//setup axios
}
async deleteEquipment(item) {
return this.axios.delete(...paths and stuff..)
}
}
export default API(config)
这对我的大部分代码都适用,除非我需要通过 props 将它交给组件,如下所示:
import API from '../path/to/api.js'
.. code
<PageTable
deleteItem={API.deleteEquipment}
...more props
/>
this
不起作用,因为它似乎在 class 中用于引用 axios 现在未定义。
this.axios
导致Cannot read properties of undefined (reading 'axios')
我尝试过后期绑定,将方法绑定到 class,如下所示:
<PageTable
...more props
deleteItem={API.deleteEquipment.bind(API)}
/>
但似乎并没有太大的作用。 任何想法如何在 PageTable 调用该方法时保持对PageTable
this
引用?
提前致谢!
尝试在构造函数中绑定 deleteEquipment
this.deleteEquipment = this.deleteEquipment(this);
还可以将 await 与异步函数一起使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.