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

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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