Ngrx用数组存储不可变状态吗? [英] Ngrx store immutable state with an array?

查看:122
本文介绍了Ngrx用数组存储不可变状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算用Angular 5创建一个大型应用程序.我也想使用Ngrx来存储我的应用程序的状态.但是有一件事我不明白.

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.

假设我有一个对象(为了简单起见,我现在不使用类或接口),它以Store表示我的状态:

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]
};

在我阅读的每篇文章中,作家都使用Object.assign()在reducer中创建状态的副本.例如:

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});
...

但这不会创建状态的深层副本.因此,新状态的y数组与旧状态的数组相同.我认为这与Redux/Ngrx的概念背道而驰.

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.

那么这是否意味着我必须使用List Immutable.js或类似的东西,并且每篇文章都是错误的"?还是我错过了什么?我认为这不是一个非常特殊的情况.

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.

推荐答案

不,您不必使用Immutable.js(我也不建议您这样做).

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]
}

在这里您会注意到两件事:
-除了使用Object.assign,您还可以将传播运算符与object
结合使用 -为了保持数组的不变性,您必须创建一个新引用.而且,您也可以仅在数组上使用散布运算符,然后仅添加一个新值.如果要在y: [4, ...state.y]之前而不是之后添加:y: [4, ...state.y],如果要删除数组中的所有3:y: state.y.filter(nb => nb !== 3)

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)

这篇关于Ngrx用数组存储不可变状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆