@嵌套对象的选择和状态的不变性 [英] @Select of nested object and immutability of state

查看:115
本文介绍了@嵌套对象的选择和状态的不变性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

示例:

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

我看到了诸如以下的解决方案:

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

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

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

提前谢谢!

推荐答案

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

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

这篇关于@嵌套对象的选择和状态的不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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