List of arrays in Redux state

This is a status question in Redux js. I have a list of arrays in state:

{
  list: list
}

According to the Redux doc, I should not change state in the reducer. I want to add a new item to the list. Should I clone the list or just add a new item to the list:

let newList = state.list;
newList.push(newItem);
return {
  list: newList
}

The above code actually changes the initial state, because newList is the same list as state.list. Is this common practice, or should I use immutableJS to clone the list?

+4
source share
2 answers

You mutate the list here and return the same link. I believe something like below should make a new copy

return { list: [...state.list, newItem] }

immutableJS. , .

deep-freeze, , .

Dan ( )

+8

, :

var newList = list.slice(); // copy the array
newList.concat(['item']);
return {
  list : newList
}
+2

Source: https://habr.com/ru/post/1622950/


All Articles