服务器端渲染后的useQuery

时间:2019-09-04 02:47:09

标签: javascript apollo next.js react-apollo apollo-client

我正在使用带有反应挂钩的next.js和apollo。

对于一页,我在服务器端渲染前X个“帖子”,如下所示:

// pages/topic.js

const Page = ({ posts }) => <TopicPage posts={posts} />;

Page.getInitialProps = async (context) => {
    const { apolloClient } = context;
    const posts = await apolloClient.query(whatever);

    return { posts };
};

export default Page;

然后在组件中,我想使用useQuery钩子:

// components/TopicPage.js

import { useQuery } from '@apollo/react-hooks';

export default ({ posts }) => {
    const { loading, error, data, fetchMore } = useQuery(whatever);

    // go on to render posts and/or data, and i have a button that does fetchMore
};

请注意,这里的useQuery执行的查询与我在服务器端为获取该主题的帖子所做的查询基本相同。

这里的问题是,在组件中,我已经从服务器传入了第一批帖子,因此我实际上不想再次获取第一批帖子,但是我仍然希望支持用户单击按钮以加载更多帖子的功能。

我考虑了在此处调用useQuery的选项,以使其从带有查询的帖子的第二个“页面”开始,但是我实际上并不希望那样。我希望主题页面在页面加载后立即完全加载我想要的帖子(即来自服务器的帖子)。

在这种情况下是否可以使useQuery工作?还是我需要避开一些人工查询(从useApolloClient到apollo客户端)的自定义逻辑?

1 个答案:

答案 0 :(得分:0)

事实证明,这只是我对nextjs服务器端渲染工作方式的误解。在将结果html发送到客户端之前,它将对React树进行完整渲染。因此,无需进行useQuery中的“第一个” getInitialProps调用或任何其他类型的调用。它仅可以单独在组件中使用,只要在服务器端配置中正确使用getDataFromTree,一切都可以正常工作。