【发布时间】:2020-01-06 21:38:48
【问题描述】:
我正在使用 next.js 和带有 react hooks 的 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 在这种情况下工作?或者我是否需要避开它来围绕手动查询调用 apollo 客户端(来自useApolloClient)的一些自定义逻辑?
【问题讨论】:
-
您应该使用
getDataFromTree根据最初在您的应用程序中呈现的查询来初始化您的商店,如here 所示。fetchMore应该会按预期工作。
标签: javascript apollo next.js react-apollo apollo-client