ham*_*huh 5 express apollo graphql next.js apollo-client
我是 NextJS 和 GraphQL 的新手,我正在使用 MERN 堆栈(NextJS 和 GraphQL)构建一个应用程序。我只需要澄清一下我是使用从查询返回的数据还是从钩子(apollo/Client)getStaticProps(nextJS)返回的数据useQuery
例如:我有一个根据 ID 获取数据的组件,它的名称是 [id].tsx,我知道在 nextJS 中我们用来在getStaticProps生成组件之前获取数据,就像在我的组件中一样
export const getStaticProps: GetStaticProps = async ({ params }) => {
let oneUserQuery = await client.query({
query: ONE_USER_QUERY,
variables: { id: params.id }
});
let user = oneUserQuery.data.userInfo;
return {
props: {
user //we fetched the userInfo and we have access to it in [id].tsx component props
}
};
};
Run Code Online (Sandbox Code Playgroud)
在组件本身中,我们可以使用 apollo/client 提供的 useQuery hook 来使用相同的 graphQL 查询来获取数据,如下所示
export default function User(props) {
//here we have access to user in the props and we can render using it
const route = useRouter();
const { loading, error, data } = useQuery(ONE_USER_QUERY, {
variables: { id: route.query.id }
});
if (error) return <div>Error loading one user.</div>;
if (loading) return <div>Loading.....</div>;
const { userInfo } = data;
return (
<Layout>
{userInfo.id} // also could be {props.user.id)
<br />
{userInfo.name} // also could be {props.user.name)
<br />
{userInfo.email} // also could be {props.user.email)
</Layout>
);
}
Run Code Online (Sandbox Code Playgroud)
两者都工作正常,我可以从两个返回值访问 userInfo 和加载状态,但哪种方法是正确的,它们之间有什么区别?
getStaticProps仅当revalidate设置选项时才更新查询结果。useQuery当apollo缓存发生变化时会自动更新。所以一般还是用比较好useQuery。如果您需要revalidate类似的行为,则可以polling在 中设置选项useQuery。
| 归档时间: |
|
| 查看次数: |
2209 次 |
| 最近记录: |