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

98
Visualizações
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 Respostas
Responde à pergunta

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 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