如何在Redux存储中重置状态值?

时间:2018-09-12 13:57:18

标签: reactjs redux-persist

我使用 redux-persist 将状态保存在本地存储中,我需要在5分钟后注销用户并将用户移至登录页面,但是我无法删除每次我尝试使用 storage.removeItem 来删除值时,redux-persist都会从本地存储中持久保存值。

RootReducer:

import storage from 'redux-persist/lib/storage';
    const appReducer  =  combineReducers({
      auth: authReducer,
      //....
    });
    const rootReducer = (state, action) => {
      if (action.type === SIGNOUT_REQUEST) {
        Object.keys(state).forEach(key => {
          storage.removeItem(`persist:${key}`);
      });
        state = undefined;
    }
    return appReducer(state, action);
    }
    export default rootReducer; 

注销操作:

export const logoutUser = () => dispatch => {
  dispatch({
    type: SIGNOUT_REQUEST
  })

APP.js

if (isTimeout) {
    store.dispatch(logoutUser());
  }

index.js

ReactDom.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
  , document.querySelector('#root')
);

1 个答案:

答案 0 :(得分:0)

您可以在分派后显式调用persistor.flush(),以告诉reducer如有必要,立即保存最新状态。

import { persistor } from 'store'; // or w/e
// ...
export const logoutUser = () => dispatch => {
  dispatch({
      type: SIGNOUT_REQUEST
  });
  persistor.flush();
}

来自the developer

  

flush用于强制尽快写入所有未决状态,并承诺等待写入解析。例如,如果您需要确保在导航之前已写入最新状态,这会很方便。