How to reset the state of a Redux store?

前端 未结 30 2583
陌清茗
陌清茗 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:40

    UPDATE NGRX4

    If you are migrating to NGRX 4, you may have noticed from the migration guide that the rootreducer method for combining your reducers has been replaced with ActionReducerMap method. At first, this new way of doing things might make resetting state a challenge. It is actually straight-forward, yet the way of doing this has changed.

    This solution is inspired by the meta-reducers API section of the NGRX4 Github docs.

    First, lets say your are combining your reducers like this using NGRX's new ActionReducerMap option:

    //index.reducer.ts
    export const reducers: ActionReducerMap = {
        auth: fromAuth.reducer,
        layout: fromLayout.reducer,
        users: fromUsers.reducer,
        networks: fromNetworks.reducer,
        routingDisplay: fromRoutingDisplay.reducer,
        routing: fromRouting.reducer,
        routes: fromRoutes.reducer,
        routesFilter: fromRoutesFilter.reducer,
        params: fromParams.reducer
    }
    

    Now, lets say you want to reset state from within app.module `

    //app.module.ts
    import { IndexReducer } from './index.reducer';
    import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
    ...
    export function debug(reducer: ActionReducer): ActionReducer {
        return function(state, action) {
    
          switch (action.type) {
              case fromAuth.LOGOUT:
                console.log("logout action");
                state = undefined;
          }
    
          return reducer(state, action);
        }
      }
    
      export const metaReducers: MetaReducer[] = [debug];
    
      @NgModule({
        imports: [
            ...
            StoreModule.forRoot(reducers, { metaReducers}),
            ...
        ]
    })
    
    export class AppModule { }
    

    `

    And that is basically one way to achieve the same affect with NGRX 4.

提交回复
热议问题