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

144
Visualizações
Value of count in state isn't incrementing

in my app,

class App extends Component {
  constructor(props){
    super(props)
    this.state={
      count:0
    }
  }
  render() {
    return (
      <div className='App-header'>
        <button onClick={()=>{this.setState({count:this.state.count=this.state.count++})}}>You Clicked This : {this.state.count} Times.</button>
      </div>
    )
  }
}

i added an event on this button :

<button onClick={()=>{this.setState({count:this.state.count=this.state.count++})}}>You Clicked This : {this.state.count} Times.</button>

but when im clicking it, value of count isn't incrementing

ps : im new to react

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

0

This has more to do with plain old javascript than react and state management.

Below is a small reproduction of your issue:

let y = 2;
y = y++;
console.log(y);
y = ++y;
console.log(y);

This is because of how ++ [(increment operator)](If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.) works.

From the docs:

If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing. If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.

Also it is note worthy that you should not do anything like:

this.state.variable = randomValue;

The fix

this.setState({count:this.state.count=++this.state.count})

will work because

this.state.count=++this.state.count

return the increment count. But state is actually updated by this.setState and you can also do:

this.setState({count:++this.state.count})

When new state value is dependent on previous value

about 4 years ago · Juan Pablo Isaza Relatório

0

In addition to above answers, when updating state, that depends on previous state, you should use callback function in state update which receives previous state and return value is updated state

this.setState(previousState => ({count: previousState.count + 1}))
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