如何解决Redux Toolkit-重置状态
按照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)
解决方法
重点是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)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。