NextJS 的 getServerSideProps 中的 Apollo 查询?

Eva*_*nss 5 apollo next.js

我将 NextJS 与 Apollo 一起使用。文档没有说太多,但指向这个存储库:https://github.com/vercel/next.js/tree/canary/examples/with-apollo

其中使用此代码:

export async function getStaticProps() {
  const apolloClient = initializeApollo()

  await apolloClient.query({
    query: ALL_POSTS_QUERY,
    variables: allPostsQueryVars,
  })

  return {
    props: {
      initialApolloState: apolloClient.cache.extract(),
    },
    unstable_revalidate: 1,
  }
}
Run Code Online (Sandbox Code Playgroud)

我发现这很丑,所以我尝试使用钩子:

const res = useQuery(ALL_POSTS_QUERY);
Run Code Online (Sandbox Code Playgroud)

但我收到一个错误:

错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。发生这种情况可能是由于以下原因之一:

那么你不能在getStaticPropsand里面使用钩子吗getServerSideProps?如果是这样,是否有更好的语法来进行 GraphQL 查询?

arc*_*att 2

您可以使用 GraphQL 代码生成器来使其变得更好。

例如,我正在做类似的事情,我的代码如下所示:

const response = await apolloClient.query<ViewerQuery>({
  query: ViewerDocument,
});
Run Code Online (Sandbox Code Playgroud)

其中ViewerQueryViewerDocument由 GraphQL 代码生成器生成。