dealing-with-react-native icon indicating copy to clipboard operation
dealing-with-react-native copied to clipboard

p757 remove 함수에서 첫번째 아이템 삭제시 빈 배열 리턴

Open yechukim opened this issue 3 years ago • 4 comments

remove(state, action) {
    const index = state.findIndex(todo => todo.id === action.payload)
    state.splice(index)
  },

책에 나온 remove 함수 부분인데요,

flter()로 하면 제대로 되는데 splice()로 했을 때, 두번째 아이템부터는 괜찮은데 맨 처음 껄 삭제하면 모든 아이템이 삭제돼요

yechukim avatar Dec 21 '21 08:12 yechukim

정확하게는 모르겠는데 불변성을 지켜주지 못해서 그런거 아닐까요 ??

splice는 원 배열을 수정합니다.(mutable)

ajrfyd avatar Jan 25 '22 05:01 ajrfyd

저렇게 책에 나와있어서 따라하는데 저런 오류가 있어서요, 혹시 오류 없으셨나요?

yechukim avatar Jan 25 '22 10:01 yechukim

redux toolkit에서 immer가 적용되어있어서 mutable하게 변경해도 업데이트는 immutable하게 작동할 것입니다.

어떤 부분이 문제일지 당장 예상이 가질 않네요..!

velopert avatar May 14 '22 17:05 velopert

@velopert

https://github.com/velopert/dealing-with-react-native/blob/86ae2979603f30692043c9942da22345fd50f01f/13/StateManagement/slices/todos.ts#L15 => initialState로 2개의 todo 가 이미 들어있기 때문에 nextId = 3 으로 변경되어야 합니다. 책에는 nextId = 3 으로 되어 있는데 여기 코드에는 nextid = 1 로 되어 있네요.

https://github.com/velopert/dealing-with-react-native/blob/86ae2979603f30692043c9942da22345fd50f01f/13/StateManagement/slices/todos.ts#L39 splice 함수의 동작이 변경된 것인지는 모르겠으나, splice(index) 의 형태로 사용하면, index를 포함하여 그 이후 모든 element 들이 제거됩니다. splice의 두번째 파라미터 deleteCount에 명시적으로 1을 입력하면 기대한대로 index element 한개만 지워집니다. state.splice(index, 1) 로 수정 필요합니다.

monibu1548 avatar Jun 13 '22 12:06 monibu1548