@Select of nested object and immutability of state

谁都会走 提交于 2020-12-15 05:41:11

问题


I am using NGXS for a while and found that if you use an object or array in @Select return it can break the immutability of the sate in the component.

Example:

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

and then two selectors:

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

I see the solution such as:

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

My question is it the right way to go? or Ngxs has some build-in solution for it.

Thanks in advance!


回答1:


you could for instance Object.freeze() in dev mode https://medium.com/ngxs/immutable-state-in-ngxs-part-i-ba318bfc5bb3



来源:https://stackoverflow.com/questions/64572841/select-of-nested-object-and-immutability-of-state

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