Redux 工具包 - 重置状态

Redux Toolkit - Reseting state

按照 Dan Abramov 的方法 ,我将如何使用 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)

重点是丹在打电话appReducer(undefined, action)。这会生成一个新的“空”状态。

您需要为此手动编写一个减速器 - 您仍然可以在其他任何地方使用 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)
}