반응형
SMALL
3.1 All you need to know about State
목표: 매번 state의 상태를 변경할 때, react가 render function을 호출해서 바꿔주길 원함
this.setState()
- state는 object
- setState는 새로운 state를 받음
- setState를 호출할 시, react는 state를 refresh하고 render function을 호출
- setState를 사용하지 않으면 새 state와 함께 render function이 호출되지 않음
this.setState({count: this.state.count+1});
- 이렇게 할 수도 있지만 state에 의존하는 것은 좋지 않음
this.setState(current=>({count: current.count+1}));
- 이것이 state를 set할 때, react에서 state에 의존하지 않는 가장 좋은 방법
class App extends React.Component
{
state={
count:0
};
add=()=>{
this.setState(current=>({count:current.count+1}));
};
minus=()=>{
this.setState(current=>({count:current.count-1}));
};
render(){
return (
<div>
<h1>The number is {this.state.count}</h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
);
}
}
export default App;
반응형
LIST
'Web 강의 > ReactJS로 영화 웹 서비스 만들기' 카테고리의 다른 글
[노마드코더/ReactJS로 영화 웹 서비스 만들기]3.0 Class Components and State (0) | 2022.03.18 |
---|---|
[노마드코더/ReactJS로 영화 웹 서비스 만들기]3.2 Component Life Cycle (0) | 2022.03.18 |
[노마드코더/ReactJS로 영화 웹 서비스 만들기]2.4 Protection with PropTypes (0) | 2022.03.18 |
[노마드코더/ReactJS로 영화 웹 서비스 만들기]2.3 map Recap (0) | 2022.03.18 |
[노마드코더/ReactJS로 영화 웹 서비스 만들기]2.2 Dynamic Component Generation (0) | 2022.03.18 |