this.setState({count: count+1}
Clicking multiple times will only update count oncethis.setState({count: this.setState.count})
Each click updates the count 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;
}
}
react@16.8.4Because 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()