2020. 6. 8. 11:17ㆍReactJS
이번 시간에는 어떻게 state를 업데이트 할 수 있을지에 대해서 배워보자!
니꼴라스 state는 단시 object 잖아!
이걸로 뭘 할 수 있다는 거야..?
니꼴라스 : 내가 add를 쓰고 싶을 때, 단지 this.state.count = 1을 할 수 있다는 걸 의미한다.
하지만 너도 보다시피, 우리는 object를 가지고 있고 이렇게 이야기해 "절대 state를 직접 변경하지 마시오."
add = () => {
console.log("add");
this.state.count = 1;
}
minus = () => {
console.log("minus");
this.state.count = -1;
}
state를 set해라. 직접 state를 변경하지 마라
나는 state를 변경하고 있지만, state는 동작하지 않고 있다!
이유는 만약에 위의 코드처럼하면, react는 render function을 refresh하지 않기 때문이다.
이 말의 의미는 매번 state의 상태를 변경할 때 너는 react가 render function을 호출해서 바꿔주길 원한다는 말이다.
만약 add를 눌러서 this.state.count = 20; 이라는 코드가 실행된다면 render() function이 다시 호출되기를 바란다는 것이다. 왜냐면 그때가지 count는 20이 되기 때문이다.
하지만 어떻게 우리가 이걸 할 수 있지? 그리고 왜 우리는 "직접 state를 변경하지 마시오"라는 메세지를 받은 것일까?
만약에 우리가 setState function을 호출하면, react는 매우 똑똑해서 우리가 언제 setState를 호출할지를 알고 또한 내가 view를 refresh하길 원하는 걸 알고 render function을 refresh하길 원하는 걸 알아
위의 방식대로 해야한다. 내가 원하는 건 내 state를 바꾸고 싶으면서 또한 react가 어떤 것이든 refresh해주길 원한다.
보다시피 setState({})는 새로운 State를 취해야한다. 그리고 이 경우에 나는 새로운 state를 줄거야
state는 object이다. 따라서 setState는 새로운 state를 받아야하고, 따라서 setState({count:1})을 하자.
import React from 'react';
import PropTypes from "prop-types";
class App extends React.Component{
state = {
// 여기에 내가 바꿀 데이터를 넣는다
count : 0
};
add = () => {
console.log("add");
// 이렇게 하면 안되고
// this.state.count = 1;
this.setState({count : 1});
}
minus = () => {
console.log("minus");
// this.state.count = -1;
this.setState({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;
왜냐면 react는 충분히 똑똑한데, 만약 너가 setState를 호출하면 react는 state를 refresh하고 또한 render funciton을 호출 할것이다.
react는 변화가 있는 부분만 업데이트할 것이다.
react는 다시 render를 호출한다.
react는 모든 걸 다시 칠하지만, 충분히 똑똑해서 처음에 이야기 했던 virtual DOM을 우리가 가지고 있기 때문에 react는 매울 빠르게 변경할 수 있고, 깜박 거리지도 않아! 보다시피, react는 state를 업데이트 했어! 또한 render function을 다시 호출 하고 있다.
이게 우리가 setState()를 사용하는 이유다!
만약 우리가 setState를 사용하지 않으면 새로운 state와 함께 render funciton이 호출되지 않을 것이다.
add = () => {
console.log("add");
// 이렇게 하면 안되고
// this.state.count = 1;
// this.setState({count : 1});
this.setState({count : this.state.count + 1});
}
minus = () => {
console.log("minus");
// this.state.count = -1;
// this.setState({count : -1});
this.setState({count : this.state.count - 1});
}
참고로 이건 좋은 코드는 아니다.
state = {
count : 0
};
왜냐하면 우리는 이 state에 의존하고 싶지 않거둔, 몇가지 성능 문제가 나중에 있기 때문이다.
지금은 counter를 이대로 둘 것이다. 나중에 더 나은 방법을 보여줄게~!
왜냐면 이렇게 state를 사용하는 것은 멋지지 않기 때문이지. react를 똑똑해서 현재의 state를 가져오는 것을 허락해줬다. function 방식으로
add = () => {this.setState(current => ({count: this.state.count + 1}))}
매우 소수만 아는 건데.! this.state.count로 하는 대신에 우리는 current를 가져와서
add = () => {this.setState(current => ({count: current.count + 1}))}
이 형태가 더 잘 동작할 것이다.
이것이 여러분이 state를 set할 때, react에서 외부의 상태에 의존하지 않는 가장 좋은 방법이다.
너가 하고 싶은 것은 current state를 얻고 싶고 react는 그것을 너에게 줄것이다. 따라서 훨씬 더 나은 새로운 state와 함께 할 수 있다. 이제 여기로 와서 refresh하면 완벽하게 동작한다.
*** 매 순간 너가 setState를 호출할 때마다 react는 새로운 state와 함꼐 render function을 호출할 것이다.
import React from 'react';
import PropTypes from "prop-types";
class App extends React.Component{
state = {
// 여기에 내가 바꿀 데이터를 넣는다
count : 0
};
add = () => {
console.log("add");
// 이렇게 하면 안되고
// this.state.count = 1;
// this.setState({count : 1});
this.setState(current => ({count : current.count + 1}));
}
minus = () => {
console.log("minus");
// this.state.count = -1;
// this.setState({count : -1});
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;
'ReactJS' 카테고리의 다른 글
#3.3 Planning the Movie Component (0) | 2020.06.08 |
---|---|
#3.2 Component Life Cycle (0) | 2020.06.08 |
#3.0 Class Components and State (0) | 2020.06.08 |
#2.4 Protection with PropTypes (0) | 2020.06.08 |
#2.3 .map Recap (0) | 2020.06.07 |