Redux 工具包迁移

Redux Toolkit Migration

我想将我使用 redux、redux-thunk 和 redux-persist 的应用程序迁移到 reduxToolkit,但我不知道如何使用我的初始配置,这里是我的代码:

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export default function getConfiguredStore(initialState, config) {
  const rootReducer = combineReducers(reducers);
  const persistedReducer = persistReducer(persistConfig, rootReducer);
  let appReducer = rootReducer;
  if (config.usePersist) {
    appReducer = persistedReducer;
  }
  const rootAppReducer = authReducer(appReducer);

  const store = createStore(
      rootAppReducer,
      initialState,
      composeEnhancers(
          applyMiddleware(
              multiClientMiddleware(axiosConfig),
              thunkMiddleware,
              authMiddleware( ),
              createLogger( true ),
          )
      ),
  );
  const persistor = persistStore(store, null, () => {
    if (config.useLogger) {
      console.log('REHYDRATED');
    }
  });
  //persistor.purge() //TO clean state.

  return {store, persistor};
}

Redux 文档中的 "Modern Redux with Redux Toolkit" tutorial page 展示了如何迁移现有的 Redux 逻辑以使用 RTK。总结:

  • 调用 configureStore()
  • 替换您现有的商店设置逻辑
  • 选择一个减速器及其相关的动作。替换为 createSlice。根据需要重复。

在您的情况下,关键部分是为此切换 const store = createStore() 部分:

  const store = configureStore({
    reducer: rootAppReducer,
    preloadedState: initialState,
    middleware: getDefaultMiddleware => {
      return getDefaultMiddleware()
        .prepend(multiClientMiddleware(axiosConfig))
        .concat(authMiddleware, createLogger( true ));
    })
  });