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

99
Vistas
React class based components update state based on previous state

I have class based components in my React application. I have a checkbox that will pass a string and a number value when checked.

My state currently looks like this:

  state = {
    checked: [],
    checkedWeight: 0,
  };

And what I could like to achieve is to append the string value passed to my handleCheckClick to my "checked" array as well as add the weight value to the total on checkedWeight (and subtract the weight and remove the string from "checked" when un-checking the box).

All variations I have tried of this create an infinite loop. For example, the next function creates an infinite loop on both cases.

 handleCheckClick = (name, weight) => {
    const joined = this.state.checked.concat(name);
    this.setState({ checked: joined });
    this.setState({ checkedWeight: this.state.checkedWeight + weight });        
  };

The next implementation does not seem to be working either:

handleCheckClick = (name, weight) => {
    this.setState(prevState => ({ checked: [...prevState.checked, name] }));
}

How can I avoid this loop without hooks?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try the following:

handleCheckClick = (name, weight) => {
  this.setState(prevState => ({ 
    checked: [...prevState.checked, name], 
    checkedWeight: prevState.checkedWeight + weight
  })
}

I can't see this causing an infinite loop. Something else might be causing that.

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