如何在配置存储中使用两个 API 减速器和 RTK 查询?

Kai*_*195 5 reactjs react-redux rtk-query

我尝试组合两个RTK减速器,但是每次尝试使用concat将其包含在中间件中时,都会出现错误,这是我的代码

商店.ts

import { configureStore,combineReducers } from "@reduxjs/toolkit";
import cartReducer from "./cartRedux";
import userReducer from "./authRedux";
import { AuthAPI } from "./authRTK";
import { cartAPI } from "./cartRTK";
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";
import storage from 'redux-persist/lib/storage'


const persistConfig = {
  key: "root",
  blacklist:['AuthAPI','cartAPI'],
  storage,
};
const rootReducer = combineReducers({
    [cartAPI.reducerPath]: cartAPI.reducer,
    [AuthAPI.reducerPath]: AuthAPI.reducer,
    auth:userReducer,
    cart:cartReducer,
})

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
//   reducer: {
//     cart: cartReducer,
//     auth: persistedReducer,
//     [api.reducerPath]: api.reducer,
//   },
  middleware: (gDM) =>
    gDM({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }).concat([AuthAPI.middleware,cartAPI.middleware]), //getDefaultMiddleware
});

export let persistor = persistStore(store);

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;

// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

报告的错误如下图所示,我无法弄清楚错误到底是什么。

我使用多个 API 的方式有问题吗?因为官方文档中没有combine版本。

phr*_*hry 6

我假设cartAPIAuthAPI都有一个reducerPathof query,导致冲突。你需要给他们不同的reducerPaths

也就是说,强烈建议您的整个应用程序中不要使用多个 api,除非这些 api 查询真正独立的数据且没有重叠。(如果查询 google 和 twitter 就是这种情况,因为它们是两家独立的公司,但如果查询帖子和评论则不会,因为它们可能是链接的)。

  • @hirro,您将无法使用自动重新获取和类似跨越多个 api 的内容,而且我非常怀疑您的实体是否 100% 彼此分离。您仍然可以使用 [代码分割](https://redux-toolkit.js.org/rtk-query/usage/code-splitting) 在多个文件中使用一个 api。 (3认同)
  • @phry 刚刚注意到这里关于“强烈建议不要在整个应用程序中使用多个 api”的评论。作为后端,我们运行带有 15 个 RestController 的 Spring Boot,每个实体一个,所有控制器都具有类似的 REST API。在构建前端时,我建议我们将每个 RestController 将 Api 分成一个块,以避免在多个人更改它时可能导致合并问题(和其他冲突)的中心文件。我们的设计选择有哪些副作用?(configureStore 变得有点混乱)。我们是否应该根据您的建议合并 API? (2认同)