一种方法是在您的应用程序中编写一个根减速器。
根减速器通常会将处理操作委托给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 操作。正如我们所知,reducers 应该在以undefined 作为第一个参数调用它们时返回初始状态,无论操作如何。让我们利用这个事实有条件地剥离累积的state,因为我们将它传递给appReducer:
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
return appReducer(undefined, action)
}
return appReducer(state, action)
}
现在,每当USER_LOGOUT 触发时,所有reducer 都会重新初始化。如果他们愿意,他们也可以返回与最初不同的东西,因为他们也可以检查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);
};