我有以下代码:
减速器:
export function testReducer(state = [], action:TestActions):any[] {
switch (action.type) {
case TestAction1Success: {
return [...action.payload];
}
case TestAction2Success: {
return [ ...state, action.payload ];
}
case TestAction3Success: {
const list = state.map(x => {
if(x.id === action.payload.id){
return action.payload
}
return x;
})
return [ ...list ];
}
default: {
return state;
}
}
}
组件:
ngOnInit() {
this.store.dispatch(new TestAction1()); // Fill store
this.list$ = this.store.select(selectList)
}
// this is a click binding to each element of this.list$ in the view
edit(listItem) {
listItem.name = "ASDASDASD" // this line also change the value in store if any action is called after this
this.store.dispatch(new TestAction2(listItem));
}
即使在化简器中仅查询“ SuccessActions”,这也会更改存储。 我可以看到为什么状态在变化。这是因为状态的默认值总是在化简器中给出。但是,如果我从商店的预订中更改了一个值,那不应该是永恒的吗?
答案 0 :(得分:1)
您有责任不这样做,而只能以不变的方式更改减速器中的状态。如果您想确保防止这种突变,则可以查看一下ngrx-store-freeze,Immutable或类似版本...
通常,您将在开发过程中使用store-freeze
,以确保代码中的任何地方(无论是组件还是化简器)都没有任何突变,然后在生产中将其关闭。