簡體   English   中英

如何在同一個反應應用程序中使用 RTK 查詢和 redux thunk?

[英]How to use RTK query and redux thunk in same react app?

我有一個要求,我必須使用 RTK 查詢來獲取數據,並使用 Redux-thunk 來進行全局 state 管理。 同樣,我創建了 2 個單獨的商店,一個用於 RTK,另一個用於 redux。 現在我面臨問題,因為我們的應用程序中不應該有 2 個商店。

商店 1:-

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import combineReducer from './combineReducer';

export const configureStore = () : any => {
  const middleWares = [thunk];
  const middlewareEnhancer = applyMiddleware(...middleWares);

  const enhancers = [middlewareEnhancer];
  const composedEnhancers: any = compose(...enhancers);

  const store = createStore(combineReducer, composedEnhancers);

  return store;
};

商店2:-


import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import { postApi } from "../services/posts";

export const store = configureStore({
  reducer: {
    [postApi.reducerPath]: postApi.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(postApi.middleware),
});

setupListeners(store.dispatch);

應用程序.tsx:-

const App: React.FC = () => (
  <Provider store={store}>
  <Provider store={rtkStore}>
    <Suspense fallback={<div>Loading...</div>}>
      <BrowserRouter>
        <Routes />
      </BrowserRouter>
    </Suspense>
  </Provider>
  </Provider>
);

我敢肯定,這其中有些可疑之處。 任何要求的解決方案都是可觀的。

Redux Toolkit 默認帶有 thunk。 您無需進行設置。 RTK 查詢內部基於 thunk。 您不能在一個應用程序中擁有多個 Redux 商店。

只需使用configureStore創建一個商店,還可以在其中添加其他減速器並將其用於所有內容。

通常,我們建議在Redux 樣式指南中為您的所有 Redux 邏輯使用 Redux 工具包,因為像createSlice這樣的幫助工具可以防止大多數常見錯誤並大量減少樣板代碼。 這是兩年多來的默認建議。

如果您還沒有閱讀官方 Redux Essentials 教程,我強烈建議您閱讀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM