简体   繁体   English

服务器端渲染后的useQuery

[英]useQuery after server-side rendering

I'm using next.js and apollo with react hooks. 我正在使用带有react挂钩的next.js和apollo。

For one page, I am server-side rendering the first X "posts" like so: 对于一页,我在服务器端渲染前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;

And then in the component I want to use the useQuery hook: 然后在组件中,我想使用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
};

Note that the useQuery here executes essentially the same query as the one I did server-side to get posts for the topic. 请注意,这里的useQuery执行与我在服务器端为获取该主题的帖子所做的查询基本相同的查询。

The problem here is that in the component, I already have the first batch of posts passed in from the server, so I don't actually want to fetch that first batch of posts again, but I do still want to support the functionality of a user clicking a button to load more posts. 这里的问题是,在组件中,我已经从服务器传入了第一批帖子,因此实际上我不想再次获取第一批帖子,但是我仍然希望支持a的功能。用户单击按钮以加载更多帖子。

I considered the option of calling useQuery here so that it starts at the second "page" of posts with its query, but I don't actually want that. 我考虑过在此处调用useQuery的选项,这样它就可以从带有查询的帖子的第二个“页面”开始,但是我实际上并不想要这样。 I want the topic page to be fully loaded with the posts that I want (ie the posts that come from the server) as soon as the page loads. 我希望主题页面在页面加载后立即完全加载我想要的帖子(即来自服务器的帖子)。

Is it possible to make useQuery work in this situation? 在这种情况下可以使useQuery工作吗? Or do I need to eschew it for some custom logic around manual query calls to the apollo client (from useApolloClient )? 还是我需要避开一些针对自定义查询(自useApolloClient )到apollo客户端的手动查询的逻辑?

Turns out this was just a misunderstanding on my part of how server side rendering with nextjs works. 事实证明,这只是我对nextjs服务器端渲染工作方式的误解。 It does a full render of the React tree before sending the resulting html to the client. 在将结果html发送到客户端之前,它将对React树进行完整渲染。 Thus, there is no need to do the "first" useQuery call in getInitialProps or anything of the sort. 因此,不需要在getInitialProps或任何类似的操作中进行“第一个” useQuery调用。 It can just be used in the component alone and everything will work fine as long as getDataFromTree is being utilized properly in the server side configuration. 它只能在组件中单独使用,只要在服务器端配置中正确使用getDataFromTree ,一切都可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM