Study/React
Update state with this.setState
더 멋진 세상을 꿈꾸는 개발자
2020. 5. 27. 15:35
Update state with this.setState
컴포넌트는 자신의 state를 단지 읽는 것보다 더 많을 것을 할 수 있다.
컴포넌트는 자신의 state를 또한 변경할 수도 있다.
컴포넌트는 this.setState() 함수를 호출함으로써 자신의 state를 변경한다.
this.setState()는 두 인자를 취한다. : object(컴포넌트의 state를 업데이트할)와 callback
당신은 기초적으로 콜백이 전혀 필요하지 않았다.
코드에디터에서, Example.js를 살펴보자.
import React from 'react';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
mood: 'great',
hungry: false
};
}
render() {
return <div></div>;
}
}
<Example />
<Example />이 가진 state에 주목해보자.
{
mood: 'great',
hungry: false
}
이제, <Example />이 호출하도록 해보자.
this.setState({ hungry: true });
호출후에, <Example />의 state는 이렇게 된다.
{
mood: 'great',
hungry: true
}
state의 mood파트는 영향을 받지 않는다!
this.setState()는 객체를 취하고, 컴포넌트의 현재 state와 객체를 병합한다.
만약 현재 state에 해당 개체의 일부가 아닌 property들이 있는 경우 해당 property은 그대로 유지된다.
https://www.codecademy.com/courses/react-101/lessons/this-state/exercises/this-setstate
| Codecademy
Codecademy is the easiest way to learn how to code. It's interactive, fun, and you can do it with your friends.
www.codecademy.com