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

181
Vistas
Why is the output different with React setState()

I don't know why

  • When I use this.setState({count: count+1} Clicking multiple times will only update count once
  • When I use this.setState({count: this.setState.count}) Each click updates the count
  • Why different?
       class Demo extends React.Component {
            state = {count: 0};
            render() {
                const {count} = this.state;
                return  <button onClick={() => this.setState({count: count+1})}>count</button>
            }
            shouldComponentUpdate(){
                return false;
            } 

        }
  • Environment react@16.8.4
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Because their scopes are different.

this.setState({count: this.setState.count+1})actions of loading state.count number and reassignment are in same onClick event scope.

But count variable in this.setState({count: count+1}) is defined in upper render() scope and onClick event only receive count as upper level variable. Therefore, render() function is only run once, so count in render() only initialized once(loading state.count only once); when you click button, only onClick event scope will be executed(reassignment actions will be executed multiple times), rather than render() scope. That is why count variable in onClick event will be always 0.

There is a simple equivalent example to your case:

state={count:0}

function upperLevel() {
  
  
  let {count} = state;

  function downlevel() {
    state = {
      count: count + 1
    }
    console.log(state);
  }

  downlevel();
  downlevel();
  downlevel();


}

upperLevel()

If we move let {count} = state; into downlevel() then the number will be increased.

state = {count: 0}

function upperLevel() {
  //let {count} = state;
  function downlevel() {
    let {count} = state;
    state = {count: count + 1 }
    console.log(state);
  }

  downlevel();
  downlevel();
  downlevel();
}

upperLevel()

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