# REACT STATE PATTERNS
## Goals
- learn how to update existing state
- properly manage state updates for mutable data structures
- best practices for modeling state and designing component
## Setting State Using State
- [setState()] is asynchronous!!
- It is risky to think previous call has finished.
- React squash together several [setState()] into one for performance reasons.
- if [setState()] refer on current state,
### => We use [callback form]
## setState Callback Form
- [this.setState(callback)]
- instead of an obj, passing a callback function w/ current state as a parameter.
this.setState(curState =>({count:curState.count+1}));
- and use functional setState
import React, { Component } from 'react';
class ScoreKeeper extends Component {
constructor(props) {
super(props);
this.state = { score: 0 };
this.singleKill = this.singleKill.bind(this);
this.tripleKill = this.tripleKill.bind(this);
}
// singleKill() {
// this.setState(state => {
// return { score: state.score + 1 };
// });
// // this is worked, but Not the Best
// // this.setState({ score: this.state.score + 1 });
// }
// tripleKill() {
// this.setState(state => {
// return { score: state.score + 1 };
// });
// this.setState(state => {
// return { score: state.score + 1 };
// });
// this.setState(state => {
// return { score: state.score + 1 };
// });
// react only read last line of these codes
// this.setState({ score: this.state.score + 1 });
// this.setState({ score: this.state.score + 1 });
// this.setState({ score: this.state.score + 1 });
// }
// functional setState
addScore(curState) {
return { score: curState.score + 1 };
}
singleKill() {
this.setState(this.addScore);
}
tripleKill() {
this.setState(this.addScore);
this.setState(this.addScore);
this.setState(this.addScore);
}
render() {
return (
<div>
<h1>Score is : {this.state.score}</h1>
<button onClick={this.singleKill}>Single Kill!</button>
<button onClick={this.tripleKill}>Triple Kill!</button>
</div>
);
}
}
export default ScoreKeeper;
'react' 카테고리의 다른 글
State exercise : lottery balls (0) | 2020.06.14 |
---|---|
More State : data structure and designing state (0) | 2020.06.14 |
State clicker exercise : who is lucky (0) | 2020.06.13 |
STATE vs PROPS (0) | 2020.06.13 |
React Events! (0) | 2020.06.13 |