객체,배열의 불변성을 유지하는 법

코드깎는 노인·2020년 4월 19일
0

javascript

목록 보기
7/8

객체 업데이트


function updateVeryNestedField(state, action) {
  return {
    ...state,
    first: {
      ...state.first,
      second: {
        ...state.first.second,
        [action.someId]: {
          ...state.first.second[action.someId],
          fourth: action.someValue
        }
      }
    }
  }
}

배열 추가,삭제

ffunction insertItem(array, action) {
  let newArray = array.slice()
  newArray.splice(action.index, 0, action.item)
  return newArray
}

function removeItem`(array, action) {
  let newArray = array.slice()
  newArray.splice(action.index, 1)
  return newArray
}

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

 [SET_SELECTEDSEATS]: (state, action) => ({
      ...state,
      selectedSeats: state.selectedSeats.concat(action.payload),
    }),

배열 업데이트

function updateObjectInArray(array, action) {
  return array.map((item, index) => {
    if (index !== action.index) {
      // This isn't the item we care about - keep it as-is
      return item
    }

    // Otherwise, this is the one we want - return an updated value
    return {
      ...item,
      ...action.item
    }
  })
}
profile
내가 볼려고 만든 블로그

0개의 댓글