@Select 嵌套对象和状态不变性
@Select of nested object and immutability of state
我使用 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 有一些内置的解决方案。
提前致谢!
例如,您可以 Object.freeze()
在开发模式下
https://medium.com/ngxs/immutable-state-in-ngxs-part-i-ba318bfc5bb3
我使用 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 有一些内置的解决方案。
提前致谢!
例如,您可以 Object.freeze()
在开发模式下
https://medium.com/ngxs/immutable-state-in-ngxs-part-i-ba318bfc5bb3