// wrong
this.state.comment = 'Hello'
대신에 setState()를 사용합니다.
// Correct
this.setState({comment: 'Hello'});
this.state
를 지정할 수 있는 유일한 공간은 바로 constructor 입니다.
React는 성능을 위해 여러 setState()
호출을 단일 업데이트로 한꺼번에 처리할 수 있습니다.
this.props
와 this.state
가 비동기적으로 업데이트될 수 있기 때문에 다음 state를 계산할 때 해당 값에 의존해서는 안 됩니다.
예를 들어, 다음 코드는 카운터 업데이트에 실패할 수 있습니다.
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
이를 수정하기 위해 객체보다는 함수를 인자로 사용하는 다른 형태의 setState()
를 사용합니다. 그 함수는 이전 state를 첫 번째 인자로 받아들일 것이고, 업데이트가 적용된 시점의 props를 두 번째 인자로 받아들일 것 입니다.
// Correct
// 화살표함수
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
// Correct
// 일반함수
this.setState(function(state, props) {
return {
counter: state.counter + props.increment
};
});
setState()
를 호출할 때 React는 제공한 객체를 현재 state로 병합합니다.
예를 들어, state는 다양한 독립적인 변수를 포함할 수 있습니다.