简体   繁体   中英

Undefined 'this' when handing class method to React component

I have API methods for my React app within an API class:

class API { 

  constructor() {
    //setup axios
  }

  async deleteEquipment(item) {
      return this.axios.delete(...paths and stuff..)
  }
}

export default API(config)

This works fine for most of my code, except when I need to hand it to components through the props, like so:

import API from '../path/to/api.js'

.. code

<PageTable
  deleteItem={API.deleteEquipment}
  ...more props
/>

This doesn't work as it seems this used in the class to reference axios is now undefined.

this.axios leads to Cannot read properties of undefined (reading 'axios')

I have tried late binding, to bind the method to the class like so:

<PageTable
  ...more props
  deleteItem={API.deleteEquipment.bind(API)}
/>

but it doesn't seem to have much effect. Any ideas how to keep the this reference to the class when the method is called by PageTable ?

Thanks in advance!

try to bind deleteEquipment in constructor

this.deleteEquipment = this.deleteEquipment(this);

also use await with async functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM