210322 개발일지(105일차) - React State 올바르게 사용하기
React의 Class에서 state를 사용할 때는 아래와 같은 3가지를 유의해야 한다.
- 직접 state 값을 수정하면 안된다. (setState 함수 사용)
- state 업데이트는 비동기적이다.
- state의 업데이트는 병합된다? (state의 변수가 여러 개라면, 따로 업데이트가 가능)
1. 직접 state 값을 수정하면 안된다. (setState 함수 사용)
만약 아래와 같이 state를 수정하면, 수정 값은 반영되나 컴퍼넌트를 다시 렌더링하지는 않는다. 즉, 올바른 사용법이 아니다.
// Wrong
this.state.comment = 'Hello';
대신 setState() 함수를 사용해야 한다.
// Correct
this.setState({comment: 'Hello'});
2. state 업데이트는 비동기적이다.
setState()를 사용할 때, 이 함수는 바로 값을 업데이트하지 않을 수 있다. (앞에 작업들이 밀려있는 이유 등)
그래서, 아래와 같이 사용하면 엉뚱한 값이 나타날 수 있다.
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
그래서, 아래와 같이 함수를 인자로 사용해야 원하는 시점의 값을 제대로 받아들인다.
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
3. state의 업데이트는 병합된다? (state의 변수가 여러 개라면, 따로 업데이트가 가능)
아래와 같이 state는 여러 독립 변수가 있을 수 있다. 또한, 이 여러 state안의 변수를 따로 업데이트 할 수 있다.
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
}
위와 같은 state가 있을 때, 아래 처럼 별도의 setState() 함수를 활용하여 독립적으로 각 state안의 변수를 업데이트 할 수 있다.
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
출처 : React 공식 페이지
Author And Source
이 문제에 관하여(210322 개발일지(105일차) - React State 올바르게 사용하기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@gojaegaebal/210322-개발일지105일차-React-State-올바르게-사용하기저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)