Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

try to bind deleteEquipment in constructor

this.deleteEquipment = this.deleteEquipment(this);

also use await with async functions

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda