一种方法是在应用程序中编写根减速器。
根减速器通常会将处理操作委托给由以下生成的减速器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
行动。众所周知,reducer 在被调用时应该返回初始状态undefined
作为第一个参数,无论采取什么行动。让我们利用这个事实来有条件地剥离累积的state
当我们将它传递给appReducer
:
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
return appReducer(undefined, action)
}
return appReducer(state, action)
}
现在,每当USER_LOGOUT
发生火灾时,所有减速器将被重新初始化。如果他们愿意的话,他们还可以返回与最初不同的东西,因为他们可以检查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 在存储引擎中保留状态的副本,并且状态副本将在刷新时从那里加载。
首先,您需要导入适当的存储引擎然后,在将其设置为之前解析状态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);
};