How to reset the state of a Redux store?

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

    My workaround when working with typescript, built on top of Dan's answer (redux typings make it impossible to pass undefined to reducer as first argument, so I cache initial root state in a constant):

    // store
    
    export const store: Store = createStore(
      rootReducer,
      storeEnhacer,
    )
    
    export const initialRootState = {
      ...store.getState(),
    }
    
    // root reducer
    
    const appReducer = combineReducers(reducers)
    
    export const rootReducer = (state: IStoreState, action: IAction) => {
      if (action.type === "USER_LOGOUT") {
        return appReducer(initialRootState, action)
      }
    
      return appReducer(state, action)
    }
    
    
    // auth service
    
    class Auth {
      ...
    
      logout() {
        store.dispatch({type: "USER_LOGOUT"})
      }
    }
    

提交回复
热议问题