본문 바로가기
JavaScript

Redux - Immutable Update Patterns

by Lalabla 2022. 2. 8.
반응형

Redux에서는 Reducer를 사용해서 현재 상태와 액션객체를 받아 새로운 상태를 리턴해준다. 

새로운 상태를 리턴해 줄 때 Immutable Data로 값을 반환해 주어야 한다.

요소를 배열에 추가하거나 지울때는 아래와 같은 방법을 사용한다.

1. 배열에 요소를 추가할 때

function insertItem(array, action) {
  return [
    ...array.slice(0, action.index),
    action.item,
    ...array.slice(action.index)
  ]
}

 

2. 배열에 요소를 삭제할 때

function removeItem(array, action) {
  return array.filter((item, index) => index !== action.index)
}

3. 배열에 요소를 업데이트 할 때

function updateObjectInArray(array, action) {
  return array.map((item, index) => {
    if (index !== action.index) {
      //해당되지 않는 경우 기존 item반환
      return item
    }

    // 해당하는 경우 업데이트 된 값 반환
    return {...item,...action.item}
  })
}

 

참조

 

Immutable Update Patterns | Redux

Structuring Reducers > Immutable Update Patterns: How to correctly update state immutably, with examples of common mistakes

redux.js.org

 

불변 업데이트 패턴 | Redux

리듀서 구조 잡기 > 불변 업데이트 패턴: How to correctly update state immutably, with examples of common mistakes

ko.redux.js.org

 

반응형

'JavaScript' 카테고리의 다른 글

Redux - React 상태 관련 라이브러리  (0) 2022.02.08

댓글