我正在使用Redux进行状态管理
例如,假设我有两个用户帐户(u1
和u2
)
用户
u1
登录到应用程序并执行一些操作,因此我们在store 中缓存一些数据.用户
u1
注销.用户
u2
在不刷新浏览器的情况下登录应用程序.
此时,缓存的数据将与u1
相关联,我想对其进行清理.
How can I reset the Redux store to its initial state when the first user logs out?个
我正在使用Redux进行状态管理
例如,假设我有两个用户帐户(u1
和u2
)
用户u1
登录到应用程序并执行一些操作,因此我们在store 中缓存一些数据.
用户u1
注销.
用户u2
在不刷新浏览器的情况下登录应用程序.
此时,缓存的数据将与u1
相关联,我想对其进行清理.
How can I reset the Redux store to its initial state when the first user logs out?个
一种方法是在应用程序中编写一个root reducer.
根减法器通常将处理动作委托给由combineReducers()
生成的减法器.但是,每当它收到USER_LOGOUT
个动作时,它都会重新返回初始状态.
例如,如果根减速器的形状如下:
const rootReducer = combineReducers({
/* your app’s top-level reducers */
})
您可以将其重命名为appReducer
,并向其写入新的rootReducer
委派:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
return appReducer(state, action)
}
现在我们只需要教新的rootReducer
返回初始状态以响应USER_LOGOUT
操作.正如我们所知,当使用undefined
作为第一个参数调用减缩器时,无论操作如何,减缩器都应该返回初始状态.让我们利用这个事实有条件地剥离累积的state
,将其传递给appReducer
:
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
return appReducer(undefined, action)
}
return appReducer(state, action)
}
现在,每当USER_LOGOUT
次 ignition 时,所有减速器都将重新初始化.如果他们愿意,他们还可以返回与最初不同的内容,因为他们也可以判断action.type
.
重申一下,完整的新代码如下所示:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
return appReducer(undefined, action)
}
return appReducer(state, action)
}
如果您使用的是redux-persist,您可能还需要清洁存储空间.Redux persist在存储引擎中保存状态副本,刷新时将从那里加载状态副本.
首先,您需要导入适当的storage engine,然后在将其设置为undefined
之前解析状态,并清除每个存储状态密钥.
const rootReducer = (state, action) => {
if (action.type === SIGNOUT_REQUEST) {
// for all keys defined in your persistConfig(s)
storage.removeItem('persist:root')
// storage.removeItem('persist:otherKey')
return appReducer(undefined, action);
}
return appReducer(state, action);
};