Ngrx store immutable state with an array?

别说谁变了你拦得住时间么 提交于 2019-12-10 18:27:17

问题


I'm planning to create a large application with Angular 5. I want to use Ngrx too to store the state of my app. But there is one thing I don't understand.

Let's say that I have an object (I don't use classes or interfaces now for simplicity), that represents my state in a Store:

let state = {
    x: 10,
    y: [1, 2, 3]
};

In every article that I read the writers are using Object.assign() to create a copy of the state in a reducer. For example:

...
case SET_X:
    return Object.assign({}, state, {x: 123});
...

But this doesn't create a deep copy of the state. So the y array of the new state is the same as the old one's. This is against the concept of Redux/Ngrx, I think.

So does this mean that I have to use List Immutable.js or something like that for example, and every article is "wrong"? Or am I missing something? I don't think that this would be a very special case.


回答1:


No you don't have to use Immutable.js (and I wouldn't recommend you to).

If you want to update the array, let say add a value, you should just do it like that:

const state = {
  x: 10,
  y: [1, 2, 3]
};

const newState = {
  ...state,
  y: [...state.y, 4]
}

Here you can notice 2 things:
- Instead of using Object.assign, you can use the spread operator with object
- To keep the immutability with an Array, you have to create a new reference. And you can also just use the spread operator on an Array and then just add a new value for example. If you wanted to add it before and not after: y: [4, ...state.y], if you wanted to remove all the 3 in the array: y: state.y.filter(nb => nb !== 3)



来源:https://stackoverflow.com/questions/48203967/ngrx-store-immutable-state-with-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!