使用Next.js动态路由时,我正试图使用路由查询对象进行SWR获取请求,但我的SWR获取请求在查询对象设置之前被调用。
考虑动态路由/posts/[id]
,页面为/posts/123
。
import { useRouter } from 'next/router';
import useSWR from 'swr';
export default function MyPage() {
const router = useRouter();
const { id } = router.query;
const url = `https://my.api.com/posts/${id}` // I've also tried using let here
const { data, error } = useSWR(url, fetcher);
console.log(url)
这个URL最开始在控制台上的日志是https://my.api.com/posts/undefined
,由于https://my.api.com/posts/undefined
显然不是有效的路径,API返回了一个错误。
紧接着,这个URL控制台上正确地记录为https://my.api.com/posts/123
,页面上的数据通常会填充,但有时数据不会填充而停留在“加载”状态。当我硬编码此URL时,从未出现过这种情况。
我在做什么错了吗?为什么查询对象不立即可用?有没有一种优雅的方式等待它被设置?