본문 바로가기

프로그램 강좌

[react.js]state 업데이트 방법


state를 사용할때 최상위 객체는 문제 없지만, 하위 객체를 건드릴때 문제가 생깁니다.

state = {
    number: 0,
    test: {
      a: 1,
      b: 2,
      c: 3
    }
  };

이런 state가 있다고 합시다.

위의 예제를 보면 number의 값은 손쉽게 바꿀 수 있지만, test 아래 a의 값을 바꾼다던가 d의 값을 추가하려면 생각과는 다른 결과를 얻게 되는거죠. 그냥 무작정 바꿔본다고 하면 이렇게 하겠죠.

this.setState({
        number: this.state.number+1,
	test: {
		d: 4
	}
})

하지만 이런 결과를 낳습니다. 기존에 있던 내용이 싹 지워지게 되죠?

이럴땐 어떻게 하면 기존 내용에서 업데이트가 가능할까요? spread 문법을 사용하면 손쉽게 바꿀 수 있어요.

App.js

import React, { Component } from 'react';

class Counter extends Component {
  state = {
    number: 0,
    test: {
      a: 1,
      b: 2,
      c: 3
    }
  };
  handleIncrease = () => {
    this.setState({
      number: this.state.number + 1,
      test: {
        ...this.state.test,  //기존 test의 내용을 모두 담은 후
        d: 4, //추가할 내용 입력
        c: 5  //이미 있는 값은 업데이트
      }
    });
  };
  render() {
    const { number } = this.state;
    const { handleIncrease } = this;
    return (
      <div>
        <h1>{number}</h1>
        <button onClick={() => handleIncrease()}>+</button>
      </div>
    );
  }
}

export default Counter;

잘 바꼈죠?







728x90