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

182
Visualizações
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 Respostas
Responde à pergunta

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