注销时重置Redux状态

时间:2019-01-15 13:11:34

标签: javascript reactjs redux react-router react-router-redux

我正在尝试解决这个问题,通常是在较早的线程-How to reset the state of a Redux store?中解决的-需要在用户注销时重新初始化/使整个redux存储无效。

但是,就我而言,仍然缺少一些东西。我将Redux与ConnectedRouter结合使用,并且尝试执行以下操作。

将rootReducer定义为:

export default history => 
  combineReducers({
    router: connectRouter(history),
    user,
    manager,
    vendor
    // rest of your reducers
  });

然后我做configureStore,将上面的内容导入为createRootReducer

const configureStore = (initialState = {}, history) => {
  let composeEnhancers = compose;
  const composeWithDevToolsExtension =
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
  const enhancers = [];
  const middleware = [sagaMiddleware, thunk, routerMiddleware(history)];
  if (typeof composeWithDevToolsExtension === 'function') {
    composeEnhancers = composeWithDevToolsExtension;
  }
  const store = createStore(
    createRootReducer(history), // root reducer with router state
    initialState,
    composeEnhancers(applyMiddleware(...middleware), ...enhancers)
  );
  store.runSaga = sagaMiddleware.run;
  store.subscribe(() => {
    const state = store.getState();
    const { session } = state['user'];
    if (!session) {
      console.log('no valid session');
      initialState = undefined;
    } else {
      const { token } = session;
      const decodedToken = jwt_decode(token);
      const { exp } = decodedToken;
      const now = new Date();
      if (exp > now.getTime()) {
        console.warn('token expired');
        initialState = undefined;
      } else {
        console.log('token valid');
      }
    }
  });
  return store;
};
export default configureStore({}, history);

想法是initialState = undefined;应该重置我的状态。但是它对我不起作用。

考虑到我正在使用ConnectedRouter并将history对象传递给它,哪里是这样做的正确位置?

2 个答案:

答案 0 :(得分:3)

在向您提供解决方案之前,我想指出一些非常重要的事情:

  1. 使用redux时,切勿尝试直接更改商店的状态。状态应始终通过减速器更改为对动作的反应。因此,在initialState回调中重新分配参数subscribe是不正确且毫无意义的。

  2. 我不认为您想“重置” router属性的状态,对吗?

解决此问题的一种方法是使用reducer增强器,如下所示:

const resetEnhancer = rootReducer => (state, action) => {
  if (action.type !== 'RESET') return rootReducer(state, action);

  const newState = rootReducer(undefined, {});
  newState.router = state.router;
  return newState;
};

然后在创建商店时执行以下操作:

  const store = createStore(
    resetEnhancer(createRootReducer(history)),
    initialState,
    composeEnhancers(applyMiddleware(...middleware), ...enhancers)
  );

然后在subscribe回调中执行以下操作:

if (!session) {
  store.dispatch({type: 'RESET'});
}

最后一个提示:由于您使用的是redux-saga,因此我强烈建议您将subscribe回调中的操作放到一个传奇中。

答案 1 :(得分:1)

您可以执行以下操作来清除商店,并在rootReducer中使用它,如下所示:


const appReducer = combineReducers({
    ... // your reducers
});

const rootReducer = (state, action) => {
    if (action.type === 'CLEAR_STORE') return appReducer(undefined, action);
    return appReducer(state, action);
};

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const configureStore = (initialState, history) =>
    createStore(
        connectRouter(history)(rootReducer),
        initialState,
        composeEnhancers(applyMiddleware(routerMiddleware(history), thunkMiddleware))
    );

您将拥有appReducer和所有减速器,还有rootReducer,这将是确定返回相应值或未定义值的函数。

  

提示:您可以使用注销操作,而不仅仅是为了清除商店而使用新操作