簡體   English   中英

反應 HOC 查詢 graphql

[英]React HOC query graphql

我需要在我的應用程序的多個頁面中查詢 graphql 並且我正在嘗試創建一個反應更高階的 function 來執行此操作。

這是原文:

const Profiles = () => {
  // Omitted code
  const { loading, error, data, refetch, fetchMore } = useQuery(
    GET_PROFILES(),
    {
      variables: { id },
    }
  );

  if (loading) {
    return <Loading />;
  }

  if (error) {
    // I need to find a way to eliminate this line because I am duplicating it on every page of my app
    if (error.message === '403: Forbidden' || error.message === '401: Unauthorized') {
      return <Redirect to="/login" />;
    }

    return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
  }

  return (
    <div>OMITTED</div>
  );
};

這就是我目前擁有的:

const WithQuery = (Comp, query, getVariables) => (props) => {
  const { loading, error, data, refetch, fetchMore } = useQuery(
    query(),
    {
      variables: getVariables(),
    }
  )

  if (loading) {
    return <Loading />;
  }

  if (error) {
    // I need to find a way to eliminate this line because I am duplicating it on every page of my app
    if (error.message === '403: Forbidden' || error.message === '401: Unauthorized') {
      return <Redirect to="/login" />;
    }

    return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
  }

  return <Comp {...props} />
}

const Profiles = WithQuery(() => {
  return (
   const {id} - useContext(UserContext);
    <div>OMITTED</div>
  );
}, GET_PROFILES, () => ({ id }));

因為這個}, GET_PROFILES, () => ({ id }));我收到一個錯誤找不到線路 ID。 如何向 hoc 發送 id 道具,以及如何從要顯示的 div 內部的查詢中訪問數據?

id未定義,因為它僅存在於您的匿名 function 組件的上下文中( WithQuery的第一個參數。它只能在定義它的 function 內部使用。

您實際上可以在getVariables() function 中使用鈎子,因此應該可以通過將const {id} = useContext(UserContext)行移動到() => ({ id }) function 來修復它。

暫無
暫無

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

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