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

235
Visualizações
this.state returning different values in console.log and display

I have a project that uses a class component to count the number of button presses. I got it to work, but when I console.log the count value, it returns a number one lower than the number displayed, even though they are using the same reference. I expected them to be the same number.

class ButtonCounter extends React.Component {
            constructor() {
                super()
                this.state = {
                    count: 0
                }
            }
            counter = 0
            getCount = () => {
                console.log('giving count')
                return this.counter
            }
            setCount = (amnt) => {
                this.counter += amnt
                this.setState({
                    count: this.counter
                })
                console.log(this.state.count) // returns -1 than the displayed value
            }
            render(){
                return(
                    <div>
                        <button onClick = {() => this.setCount(1)}>{this.state.count}</button>
                    </div>
                )
            }
        }

image of the code in browser

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

0

As stated in react docs

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied

Source: https://reactjs.org/docs/react-component.html#setstate

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