首页 > 解决方案 > React HOC 查询 graphql

问题描述

我需要在我的应用程序的多个页面中查询 graphql,并且我正在尝试创建一个反应高阶函数来执行此操作。

这是原文:

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 内部的查询中访问数据?

标签: javascriptreactjs

解决方案


id未定义,因为它仅存在于您的匿名函数组件的上下文中( . 它的第一个参数WithQuery。它只能在定义它的函数内部使用。

您实际上可以在getVariables()函数中使用钩子,因此应该可以通过将const {id} = useContext(UserContext)行移到() => ({ id })函数中来修复它。


推荐阅读