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

73
Visualizações
Splice an array in React keeps rerendering

In the update(changeProps) function, I have something like this:

 update(changedProps) {
      if (this.person) {
        this.__arr = ['hi', 'hi', 'hi'];
      } else {
        this.__arr = ['bye', 'bye', 'bye', 'bye'];
      }

    if (this.__hello) {
      this.__arr.splice(1, 0, 'hello');
    }

    super.update(changedProps);
  }

Say this.person is true, when I click elsewhere and the page rerenders, it becomes

this.__arr = ['hi', 'hello', 'hi', 'hi']

Then when it rerenders again: this.__arr = ['hi', 'hello','hello', 'hi', 'hi']

It keeps adding to the array after each rerender. Same for if this.person is not true. How do I make it so it only adds it once?

If I did something like this: this.__arr = [...this.__arr, 'hello'], it can add it to the end, but I want to add an element to index 1

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

0

Two things:

  1. Don't mutate:
    if (this.__hello) {
      this.__arr = [...this.__arr].splice(1, 0, 'hello');
    }
  1. Do you want to do this every time the component updates, or just once?
    if (this.__hello && this.__arr[1] !== 'hello') {
      this.__arr = [...this.__arr].splice(1, 0, 'hello');
    }
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