Last active
June 7, 2019 19:03
-
-
Save ralfting/9d5145c53c03fb5b042819715654328e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| class App extends React.Component { | |
| state = { | |
| counter: 0, | |
| } | |
| componentDidMount() { | |
| // if used in here, that's works well without need to pass a CB in the second argument of setState | |
| // that's because the setState in this context is synchronous | |
| // setInterval(() => { | |
| // this.increment(); | |
| // }, 3000) | |
| } | |
| componentDidUpdate() { | |
| console.log('updated', this.state); | |
| } | |
| logMe = () => { | |
| console.log(this.state.counter); | |
| } | |
| increment = () => { | |
| // works in both scenarios | |
| this.setState(state => ({ counter: state.counter + 1 })); | |
| this.setState(state => ({ counter: state.counter + 1 }), this.logMe); // use a callback to get state just when is updated | |
| } | |
| incrementOutDated = () => { | |
| // When is trigged for a non-behavior of the user, the setState is executed synchronous | |
| this.setState(state => ({ counter: state.counter + 1 })); | |
| this.setState(state => ({ counter: state.counter + 1 })); | |
| console.log(this.state.counter); | |
| } | |
| render() { | |
| return ( | |
| <div className="App"> | |
| {/* using this.increase works well */ } | |
| {/* When the action come from a behavior of the user, the setState is executed asynchronous */ } | |
| <button onClick={this.incrementOutDated}>Add 1 more</button> | |
| <h3>{this.state.counter}</h3> | |
| </div> | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment