@选择嵌套对象和状态不变

时间:2020-10-28 12:27:10

标签: angular immutability deep-copy state-management ngxs

我使用NGXS一段时间,发现如果在@Select return中使用对象或数组,则可能破坏组件中对象的不变性。

示例:

state: AppStateModel = {
  justValue: true,
  complexObject: { a:1, b:2}
}

,然后是两个选择器:

// Here in a component we will get access to object by link and can modify it in state without patchState or setState
  @Selector()
  static getComplexObject(state: AppStateModel) {
    return state.complexObject;
  }

// That will work fine since JS will return it as a value (simple types) not a link
  @Selector()
  static getJustValue(state: AppStateModel) {
    return state.justValue;
  }

我看到了解决方案,例如:

  // Here we can apply DeepCopy method to decople object from the state, and keep immutability no matter what happens in the components
  @Selector()
  static getComplexObject(state: AppStateModel) {
    return clone(state.complexObject);
  }

我的问题是正确的方法吗?或Ngxs有一些内置的解决方案。

谢谢!

1 个答案:

答案 0 :(得分:1)

例如,您可以在开发人员模式下使用Object.freeze() https://medium.com/ngxs/immutable-state-in-ngxs-part-i-ba318bfc5bb3