簡體   English   中英

將 SWR 與 Redux 一起使用是正確的還是良好的做法?

[英]Is it correct or good practice to use SWR together with Redux?

我正在使用SWR

在我的代碼中,我使用兩者的連接點如下

const vehiclesStates = useSelector(({ vehiclesStates: state }) => state); // REDUX
const response = useFetch("/vehicles/states") // SWR
const dispatch = useDispatch(); // REDUX

// REDUX
useEffect(() => {
  if(response.data) dispatch(VehiclesStatesActions.setVehiclesStates(response.data.result))
}, [response.data, dispatch]);

if(response.error) return <div>ERROR - {response.error.toString()}</div> // SWR
else if(!response.data) return <div>LOADING</div> // SWR

// If there is a return I render my component
return (<></>)

在上面的這段摘錄中,我將我的組件 state 設置在 redux 中,並使用我使用 SWR(與 axios 集成)返回的數據。 這樣,在需要使用相同數據的任何其他組件中,我只使用 redux 的useSelect導入它。

這邊走

const vehiclesStates = useSelector(({ vehiclesStates: state }) => state);

我發現它比通過在每個想要使用該數據的組件上調用 useFetch 來使用 SWR 更實用。

我的問題是:使用這種方式是正確的方式,還是會影響性能或其他什么?

提前致謝

I think that's a little redundant, you could be better using one or the other, SWR is intended to use the cache as a local state, because that state lives on the server it's more adecuated and frees you from managing every manipulation in the state verbosely ,就像你必須做的 redux 明確調用 API 調用任何時候你調度一個動作。

使用這兩種破壞SWR的目的,你最好只使用Redux。 一個好的規則是使用 SWR 管理服務器中的 state,並使用 Redux 管理本地 state。

在某些情況下,我可以看到兩者並存,即當您進行非常復雜的數據操作時,您必須經常修改和刪除信息,我認為這種情況將使用 redux 和 SWR 的變異 function 的某種組合。

您可以將 swr 與 redux 一起使用,這不是多余的。 因為state有2種。 UI StateServer Caching State Ui state 的一個示例是模態是打開還是關閉。 服務器緩存 State,我們稱之為 api,存儲結果並緩存該結果以供客戶端使用。 swr正在處理服務器緩存 State。

redux早期,沒有緩存。 然后出現了一些庫,在 next.js swr 中,在 react-query 庫中。 Redux-toolkit有自己的 api 緩存實現。

我認為使用 React-16,我們得到了上下文 api。 React 上下文本身並不是一個 state 管理工具。 這只是傳輸數據的一種手段。 如果與useStateuseReducer一起使用,它將成為 state 管理工具。 將 React Context 與你自己的 hooks 結合,你可以替換 redux。 在你的鈎子函數中你應該使用swr 我在這里解釋了如何結合 react-context、hooks 和 swr 來創建一個完整的 state 管理工具: 全局 state 管理和 Next.js

來自后端的響應可能有一個項目列表。 SWR 方法將迫使您重新繪制所有使用列表中的項目的元素,或者創建一組相等比較器和/或上下文,這些比較器和/或上下文足夠聰明,可以判斷 DOM 的哪個部分應該更新或不更新。

Redux 也需要一些努力來保證道具的穩定性。 然而,人們可以使用提供的 useSelector + shallowEqual 來提取所需的最小值。 這是 List 組件的 id 列表和卡片組件中的 row by id。

請查看代碼。 恕我直言,這兩種方法不是直接競爭對手。

話雖如此,請記住有一些庫(順便提一下,Material-UI)可以為您管理列表。 如果您使用其中之一,請使用他們的建議來優化重繪(如果需要)。

    import { FC } from "react";
    import { shallowEqual, useSelector } from "react-redux";
    import useSWR from "swr"

    interface CardInfo {
      id: number;
      name: string;
      price: number;
    };
    type RootState = Array<CardInfo>;

    declare const fetcher: () => Promise<CardInfo[]>

    const CardView: FC<CardInfo> = (p) => (<pre>{JSON.stringify(p)}</pre>);

    const CardById: FC<Pick<CardInfo, "id">> = ({ id }) => {
      const card = useSelector((rootState: RootState) => rootState.find((c) => c.id === id), shallowEqual)
      if (typeof card === "undefined") {
        return null;
      }
      return <CardView {...card} />
    }

    export const ListSwr: FC = () => {
      const { data } = useSWR(
        "/api/cards",
        fetcher,
        /*{compare: NO FANCY COMPARE HELPS 
          WHEN ONLY ONE OF MANY ITEMS CHANGED}*/
      );
      if (!Array.isArray(data)) {
        return null;
      }
      return (<>
        {data.map((c) => (<CardView key={c.id} {...c} />))}
      </>)
    }

    export const ListFromStore: FC = () => {
      const ids = useSelector((rootState: RootState) => rootState.map(e => e.id), shallowEqual)
      return (<>
        {ids.map((id) => <CardById key={id} id={id} />)}
      </>)
    }

暫無
暫無

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

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