【发布时间】:2020-01-26 13:02:43
【问题描述】:
当我们有不同的减速器时,重置整个状态的最佳方法是什么? 我在使用选择器时遇到了这个问题,因为当我重置时它不会给我带来初始状态
元减速器
import { ActionReducer } from '@ngrx/store';
import { UserActionTypes } from '../../actions/actionTypes';
export function clearStateReducer(reducer: ActionReducer<any>): ActionReducer<any> {
return (state, action) => {
if (action.type === UserActionTypes.Logout) {
state = undefined;
}
return reducer(state, action);
};
}
状态模块
import { NgModule } from '@angular/core';
import { StateService } from './state.service';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { StoreModule } from '@ngrx/store';
import { appReducer } from './reducers';
import { getInitialState } from './state';
import { metaReducers } from './reducers/metaReducers';
@NgModule({
imports: [
StoreModule.forRoot(appReducer, {
initialState: getInitialState(),
metaReducers,
runtimeChecks: {
strictStateImmutability: false,
strictActionImmutability: false,
strictStateSerializability: false,
strictActionSerializability: false
}
}),
StoreDevtoolsModule.instrument({
maxAge: 25
})
],
providers: [StateService]
})
export class StateServiceModule {}
【问题讨论】:
-
你目前的做法是什么?
-
刷新页面将以初始ngrx状态启动应用程序。除此之外,您可能还想使用 meta-reducer。第三种选择是为每个 reducer 添加一个新动作和新案例,并从 resetState$ 效果中触发它们。
-
你能在 stackblitz 中分享你的代码吗?你在使用本地存储吗?
-
我正在使用这个 metaReducer - 导出函数 clearStateReducer(reducer: ActionReducer
): ActionReducer { return (state, action) => { if (action.type === UserActionTypes.Logout ) { 状态 = 未定义; } 返回减速器(状态,动作); }; } -
@Jose 那么有什么问题 - 它应该重置整个状态。