Created
December 18, 2019 10:47
-
-
Save Goloburda/d634172dbbe8959c5ec6875dd92d4484 to your computer and use it in GitHub Desktop.
React setState
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The setState() method does not immediately update the state of the component, | |
it just puts the update in a queue to be processed later. | |
React may batch multiple update requests together to make rendering more efficient. | |
Due to this, special precautions must be made when you try to update | |
the state based on the component's previous state. | |
*/ | |
state = { count: 1 }; | |
componentDidMount() { | |
// this.setState({ count: this.state.count + 1 }); | |
// this.setState({ count: this.state.count + 1 }); | |
// this.setState({ count: this.state.count + 1 }); | |
// count = 1; | |
/* | |
Object.assign( | |
{}, | |
{ count: this.state.count + 1 }, | |
{ count: this.state.count + 1 }, | |
{ count: this.state.count + 1 }, | |
) | |
*/ | |
this.setState(prevState => ({ count: prevState.count + 1 })); | |
this.setState(prevState => ({ count: prevState.count + 1 })); | |
this.setState(prevState => ({ count: prevState.count + 1 })); | |
//count = 4 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment