问题
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