불변성 - ...Spread Operator vs. Object.assign()

moontag·2022년 7월 6일
0

Redux

목록 보기
2/4

immutability 불변성

Redux의 state객체 업데이트는 immutable하게 변경해야 한다.
원본 객체가 아니라 복사본에서 업데이트를 하도록 만든다.

불변 업데이트란? => 얕은 복사본을 만드는 것 (깊은 복사 아님!!)




1. Object Spread Operator

function todoApp(state = initialState, action) {
  const filtered = state.cartItems.filter(
        (el) => el.itemId !== action.payload.itemId
      );
  switch (action.type) {
    case REMOVE_FROM_CART:
      return { ...state, cartItems: filtered, }
    default:
      return state
  }
}
  • ...spead 로 객체 복사



2. Object.assign()

function todoApp(state = initialState, action) {
  const filtered = state.cartItems.filter(
        (el) => el.itemId !== action.payload.itemId
      );
  switch (action.type) {
    case REMOVE_FROM_CART:
      return Object.assign({}, state, {
        cartItems: filtered,
      });
    default:
      return state
  }
}
  • {} 빈 객체에 state 속성들 복사하고 {변경사항}을 추가

참고

https://redux.js.org/usage/structuring-reducers/immutable-update-patterns

profile
터벅터벅 나의 개발 일상

0개의 댓글