使用 useSWR 的 Next.js 动态页面
我想使用 useSWR 和 useRouter 基于 Saloon 配置文件的 ID 创建动态页面,但数据在页面渲染后加载。
这是我的代码:
import useSWR from "swr";
import { useRouter } from "next/router";
const fetcher = (url) => fetch(url).then((res) => res.json());
export default function FindSaloonProfile() {
const router = useRouter();
const { id } = router.query;
const { data, error } = useSWR(
id ? `/api/getSaloons` : null,
id ? fetcher : null
);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <>Hello {data.name} </>;
}
如果我 console.log(data)
,它开始获取 undefined
并随后加载数据,但为时已晚,因为页面是已经渲染了。
我做错了什么?
I want to create dynamic pages based on the ID of a Saloon profile using useSWR and useRouter, but the data loads in after the pages are rendered.
This is my code:
import useSWR from "swr";
import { useRouter } from "next/router";
const fetcher = (url) => fetch(url).then((res) => res.json());
export default function FindSaloonProfile() {
const router = useRouter();
const { id } = router.query;
const { data, error } = useSWR(
id ? `/api/getSaloons` : null,
id ? fetcher : null
);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <>Hello {data.name} </>;
}
If I console.log(data)
, it starts getting undefined
and loads in the data afterward, but then it is too late, as the page is already rendered.
What do I do wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将 fetcher 包装在一个函数中:
Wrap the fetcher in a function:
Next.js 是服务器端渲染框架,但大多数 SWR 仅在客户端工作,因此这意味着 API 在页面加载(或 Javascript 加载)之前不会获取数据。
最近,SWR 发布了 Next.js 集成的新文档。你可以在这里查看。
https://swr.vercel.app/docs/with-nextjs
让我试试简而言之,
getStaticProps
将帮助您在服务器端获取数据之后,您需要导入
SWRConfig
进行fallback
这是为了获取的数据(React-Next.js Hydration 可以帮助您将数据与 React 的上下文链接起来)最后,您只需拥有常用的组件
希望我的答案能够帮助您
Next.js is the server-side rendering framework, but mostly SWR works on the client-side merely, so it means API won't fetch data till the page loaded (or Javascript loaded).
Recently, SWR has published a new document for Next.js integration. You can check it out here.
https://swr.vercel.app/docs/with-nextjs
Let me try to keep it in a short explanation
getStaticProps
will help you to get data on the server-sideAfter that, you need to import
SWRConfig
forfallback
which is for the fetched data (React-Next.js hydration with help you to link your data with React's context)Lastly, you just have your usual component
Hopefully, my answer is able to help you