[英]How to reset value of state in a Redux store?
我使用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')
);
您可以在调度后显式调用persistor.flush()
来告诉减速器在必要时立即保存最新状态。
import { persistor } from 'store'; // or w/e
// ...
export const logoutUser = () => dispatch => {
dispatch({
type: SIGNOUT_REQUEST
});
persistor.flush();
}
来自开发商:
flush
旨在强制尽快写入所有未决状态,并提供等待写入解决方案的承诺。 例如,如果您需要确保在离开之前写入最新状态,这可能会很方便。
要“重置”整个 redux-persist 存储,请使用purge()
persistor.purge()
"
purge()
方法只清除存储的内容,不影响 redux 的内部数据"
如前所述,
flush()
是错误的,仅刷新挂起状态:“flush() 方法用于刷新所有挂起状态序列化并立即写入磁盘”
https://nicedoc.io/rt2zz/redux-persist/blob/master/docs/api.md
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.