setState()

김민석·2021년 3월 21일
0

react

목록 보기
2/11

setState()에 대한 React 공식 문서
setState()에 대한 더 자세한 공식 문서


React를 배우면서

this.setState()와 마주쳤다.
이 메소드는 html에 렌더링 되는 요소들 중, 변경이 될 수 있는 this.state에 저장된 모든 요소의 값을 변경할 때 사용되는 함수로 볼 수 있을 것 같다.

그런데 this.setState()에 몇 가지 용법이 있는 것 같아서 기억해 두기위해 적어둔다.


몇 가지 용법

syntax

this.setState(updater,[callback])

우선 setState는 즉각적인 명령이라기보다는 요청이다.
따라서, 즉각적으로 갱신되는게 아니다.

incrementCount() {
  // Note: this will *not* work as intended.
  this.setState({count: this.state.count + 1});
}

handleSomething() {
  // Let's say `this.state.count` starts at 0.
  this.incrementCount();
  this.incrementCount();
  this.incrementCount();
  // When React re-renders the component, `this.state.count` will be 1, but you expected 3.

  // This is because `incrementCount()` function above reads from `this.state.count`,
  // but React doesn't update `this.state.count` until the component is re-rendered.
  // So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.

그러므로 위 코드에서 결과 값은 1이 나온다.

updater

updater의 syntax는 다음과 같다.
(state, props) => stateChange

  • state
    state은 변경 사항이 적용되는 시점 직전의 state를 의미하며, 이 때의 states는 항상 이전 값이 반영된 값임을 보장한다.
    따라서 아래와 같은 행위가 예상대로 동작한다.
incrementCount() {
  this.setState((state) => {
    // Important: read `state` instead of `this.state` when updating.
    return {count: state.count + 1}
  });
}

handleSomething() {
  // Let's say `this.state.count` starts at 0.
  this.incrementCount();
  this.incrementCount();
  this.incrementCount();

  // If you read `this.state.count` now, it would still be 0.
  // But when React re-renders the component, it will be 3.
}

0개의 댓글