How to reset the state of a Redux store?

前端 未结 30 2349
陌清茗
陌清茗 2020-11-22 06:20

I am using Redux for state management.
How do I reset the store to its initial state?

For example, let’s say I have two user accounts (u1 and

30条回答
  •  耶瑟儿~
    2020-11-22 06:32

    The following solution worked for me.

    I added resetting state function to meta reducers.The key was to use

    return reducer(undefined, action);
    

    to set all reducers to initial state. Returning undefined instead was causing errors due to the fact that the structure of the store has been destroyed.

    /reducers/index.ts

    export function resetState(reducer: ActionReducer): ActionReducer {
      return function (state: State, action: Action): State {
    
        switch (action.type) {
          case AuthActionTypes.Logout: {
            return reducer(undefined, action);
          }
          default: {
            return reducer(state, action);
          }
        }
      };
    }
    
    export const metaReducers: MetaReducer[] = [ resetState ];
    

    app.module.ts

    import { StoreModule } from '@ngrx/store';
    import { metaReducers, reducers } from './reducers';
    
    @NgModule({
      imports: [
        StoreModule.forRoot(reducers, { metaReducers })
      ]
    })
    export class AppModule {}
    

提交回复
热议问题