Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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>
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement