首页 > javascript > 使用ngrx或ngxs时,我们是否自动获得对象不变性?

使用ngrx或ngxs时,我们是否自动获得对象不变性? (Do we get object immutability automatically when using ngrx or ngxs?)

问题

使用NGRXNGXS时,我们是否自动获得所有域实例的对象不变性?我读到的大多数上下文似乎表明了这一点,但也有类似“当我们使用带有不可变对象的NGRX ......”这样的措辞时,所以只想仔细检查我们是不是想要使用类似的东西immutable.js除了NGRX?

解决方法

在处理开发模式时,NGXS确实使用不可变对象。请参考ngxs / store repo中的state-operations.ts文件来验证这一点。

从第36行开始并按照代码:

if (this._config.developmentMode) {
  return this.ensureStateAndActionsAreImmutable(rootStateOperations);
}

ensureStateAndActionsAreImmutable那里有deepFreeze()一个Object.freeze(value)on值。

因此在使用ngx时不需要immutable,immer或任何不可变库。

如果你使用NGRX,你可能想使用ngrx-store-freeze而不是第三方库。这有一个依赖(深度冻结 - 严格),将确保不变性。

问题

Do we automatically get object immutability for all domain instances when using NGRX or NGXS? Most of the contexts that I read up on seem to indicate this, but there's also wording like"When we use NGRX with immutable objects ...", so just want to double check that we are not suppose to use something like immutable.js in addition to ngrx?

解决方法

NGXS does use immutable objects when working on development mode. Please refer to state-operations.ts file in ngxs/store repo to verify this.

Start in line 36 and follow the code:

if (this._config.developmentMode) {
  return this.ensureStateAndActionsAreImmutable(rootStateOperations);
}

In ensureStateAndActionsAreImmutable there is deepFreeze() which does an Object.freeze(value) on values.

So no need for immutable, immer or any immutable library when using ngxs.

If you go with NGRX, you might want to use ngrx-store-freeze instead of third party libs. This has one dependency(deep-freeze-strict) that will ensure immutability.

相似信息