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

311
Visualizações
React JS onChange function of Material UI 'number' TextField uses previous value

I have an onChange function on this element:

<TextField id="rowinput" type="number" 
           defaultValue={this.defaultRows} // defaultrRows = 1
           inputProps={{ min: "1", max:"5"}}
           onChange={this.handleRows}>
</TextField>

This is the function:

handleRows = ev => {
        let newrows = ev.target.value;
        let newcount = newrows * this.state.cols;
        this.setState( {rows: newrows, panelcount: newcount} )
        console.log("Row Count: " + this.state.rows);
        console.log("Total Count: " + this.state.panelcount);
}

What this should do is take the value of the input field when the up and down arrows are clicked, and update the state. However, I've found that when the console statement in the handler prints its result, the number used is one step behind.

As you can see, on page load it starts with a default value of 1 (as does the cols value it is referencing), and so when the up arrow is clicked, the value changes to 2 and it should print out:

Row Count: 2

Total Count: 2

When I print the temporary variables it prints 2 and 2, but when I use the state call here, it prints 1 and 1. Here for example, I increased the value up to 5, and you can see the console never logged higher than 4:

enter image description here

enter image description here

Is the state update called asynchronously? How can the temporary variables be correct but calling this.state.rows is one iteration behind?

Any help would be greatly appreciated

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

0

When using setState the state is not actually updated until the next render. Your console log is in the same function and occurs before the re-render after state is updated. If you were to do the console.log outside of the function you will see that the state is updated.

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