Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

67
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda