我正在使用 next.js
和带有 React Hook 的 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
钩子(Hook):
// 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
)的一些自定义逻辑?
最佳答案
事实证明,这只是我对使用 nextjs 进行服务器端渲染的方式的误解。在将生成的 html 发送到客户端之前,它会完整呈现 React 树。因此,无需在 getInitialProps
或任何类似的操作中执行“第一次”useQuery
调用。它可以单独在组件中使用,只要在服务器端配置中正确使用 getDataFromTree
,一切都会正常工作。
关于javascript - 服务器端渲染后的useQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57780847/