简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM