【问题标题】:Redux Toolkit - Reseting stateRedux Toolkit - 重置状态
【发布时间】:2020-12-14 23:04:46
【问题描述】:

按照 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)

【问题讨论】:

    标签: redux redux-toolkit


    【解决方案1】:

    关键是丹正在打电话给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)
    }
    

    【讨论】:

    • 当我从注销处理程序调度此操作时,似乎什么也没发生。 await dispatch(resetAction()) 不调用 resettableReducer。
    • 您现在使用的是resettableReducer 而不是reducer?它是 reducer 周围的一个 wapper,所以在你之前使用 reducer 的任何地方,你现在都应该使用 resettableReducer,否则它永远不会被调用。例如在您的 persistedReducer 定义中。
    • 啊,是的,你是对的。猜猜这不是很明显。谢谢!
    • 如果你有一个authorizationSlice,你就不能在那个slice 中写一个reducer 并在调用logout() 函数时将它的状态设置为undefined 吗?例如,logout : state => { state = {userInfo: {}, expiresAt: null, isLoggedIn: false} } 或简单的 logout : state => { state = undefined}
    猜你喜欢
    • 2020-04-12
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2022-01-01
    • 2020-08-04
    • 2021-04-22
    • 2021-04-15
    相关资源
    最近更新 更多