【问题标题】:difference between result from useQuery hook (apolloClient) and getStaticProps (NextJS)useQuery hook (apolloClient) 和 getStaticProps (NextJS) 结果之间的区别
【发布时间】:2020-11-20 02:06:42
【问题描述】:

我是 NextJS 和 GraphQL 的新手,我正在使用 MERN 堆栈和(NextJS 和 GraphQL)构建一个应用程序。 我只需要澄清一下我是使用getStaticProps(nextJS)中的查询返回的数据还是useQuery钩子(apollo/Client)返回的数据

例如:我有一个根据 ID 获取数据的组件,它的名称是 [id].tsx, 我知道在 nextJS 中我们使用getStaticProps 在组件生成之前获取数据, 在我的组件中就像这样

export const getStaticProps: GetStaticProps = async ({ params }) => {

  let oneUserQuery = await client.query({
    query: ONE_USER_QUERY,
    variables: { id: params.id }
  });

  let user = oneUserQuery.data.userInfo;

  return {
    props: {
      user   //we fetched the userInfo and we have access to it in [id].tsx component props
    }
  };
};

在组件本身中,我们可以使用 apollo/client 提供的 useQuery 钩子来获取具有相同 graphQL 查询的数据,就像这样

export default function User(props) {
//here we have access to user in the props and we can render using it

  const route = useRouter();

  const { loading, error, data } = useQuery(ONE_USER_QUERY, {
    variables: { id: route.query.id }
  });

  if (error) return <div>Error loading one user.</div>;
  if (loading) return <div>Loading.....</div>;

  const { userInfo } = data;

  return (
    <Layout>
      {userInfo.id}       // also could be {props.user.id)
      <br />
      {userInfo.name}     // also could be {props.user.name)
      <br />
      {userInfo.email}    // also could be {props.user.email)
    </Layout>
  );
}

两者都工作正常,我可以从两个返回值访问 userInfo 和加载状态,但哪种方法是正确的,它们之间有什么区别?

【问题讨论】:

  • 我也有同样的问题,你解决了吗?
  • @MarkSteggles 不是真的,我只是在不同的组件中使用了这两种组件,因为我不知道有什么区别,如果你知道了,我希望你在这里添加你的答案,抱歉回复晚了

标签: express graphql next.js apollo apollo-client


【解决方案1】:

getStaticProps 仅在设置revalidate 选项时更新查询结果。 useQuery 将在 apollo 缓存更改时自动更新。所以一般最好使用useQuery。如果您需要revalidate 类似的行为,则可以在useQuery 中设置polling 选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2022-10-24
    • 2012-11-07
    • 2019-02-14
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多