0

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

根减速器:

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')
);
4

2 回答 2

2

您可以persistor.flush()在调度后显式调用以告诉减速器在必要时立即保存最新状态。

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

来自开发商

flush旨在强制尽快写入所有未决状态,并提供等待写入解决方案的承诺。例如,如果您需要确保在离开之前写入最新状态,这可能会很方便。

于 2018-09-12T14:23:56.530 回答
1

要“重置”您的整个 redux-persist 存储使用purge()

persistor.purge()

flush()如前所述是错误的,只刷新挂起状态:“flush() 方法用于刷新所有挂起的状态序列化并立即写入磁盘”而“purge()方法只清除存储的内容,而不影响 redux 的内部数据”

https://nicedoc.io/rt2zz/redux-persist/blob/master/docs/api.md

于 2022-02-25T08:28:45.317 回答