按照Dan Abramov的方法here,我如何使用RTK清除我的整个应用程序状态?
丹的建议
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
我的方法-(不知道我在做什么)
const reducer = combineReducers({
user,
post,
})
const clearState = createAction('CLEAR_STATE')
const rootReducerRTK = createReducer(
{},
{
[clearState.type]: state => (state = undefined), // this is wrong for sure
},
)
const persistedReducer = persistReducer(persistConfig, reducer)
// ignore all the action types from redux-persist as specified in the docs
export const store = configureStore({
reducer: persistedReducer,
middleware: getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
})
export const persistor = persistStore(store)
答案 0 :(得分:3)
重点是Dan在呼叫appReducer(undefined, action)
。这将产生一个新的“空”状态。
您需要为此手动编写一个reducer-您仍然可以在其他任何地方使用RTK。
const reducer = combineReducers({
user,
post,
})
const resetAction = createAction('reset')
const resettableReducer = (state, action) => {
if (resetAction.match(action) {
return reducer(undefined, action)
}
return reducer(state, action)
}