Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. class App extends React.Component {
  2. state = {
  3. counter: 0,
  4. }
  5.  
  6. componentDidMount() {
  7. // if used in here, that's works well without need to pass a CB in the second argument of setState
  8. // that's because the setState in this context is synchronous
  9.  
  10. // setInterval(() => {
  11. // this.increment();
  12. // }, 3000)
  13. }
  14.  
  15. componentDidUpdate() {
  16. console.log('updated', this.state);
  17. }
  18.  
  19. logMe = () => {
  20. console.log(this.state.counter);
  21. }
  22.  
  23. increment = () => {
  24. // works in both scenarios
  25. this.setState(state => ({ counter: state.counter + 1 }));
  26. this.setState(state => ({ counter: state.counter + 1 }), this.logMe); // use a callback to get state just when is updated
  27. }
  28.  
  29. incrementOutDated = () => {
  30. // When is trigged for a non-behavior of the user, the setState is executed synchronous
  31. this.setState(state => ({ counter: state.counter + 1 }));
  32. this.setState(state => ({ counter: state.counter + 1 }));
  33.  
  34. console.log(this.state.counter);
  35. }
  36.  
  37. render() {
  38. return (
  39. <div className="App">
  40. {/* using this.increase works well */ }
  41. {/* When the action come from a behavior of the user, the setState is executed asynchronous */ }
  42. <button onClick={this.incrementOutDated}>Add 1 more</button>
  43. <h3>{this.state.counter}</h3>
  44. </div>
  45. );
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement