Next.js 为 Link 组件中的嵌套动态路由添加当前路径
Next.js prepending current path for nested dynamic routes in Link components
您将如何处理嵌套动态路由并使用 Next.js Link 组件?
假设我有 2 个文件路径:
/pages/projects/index.js
<Link href={`/projects/${project.id}`} key={index}>
<a>Project Name</a>
</Link>
这会带我去 localhost:3000/projects/some-id/
和
/pages/projects/[pid]/index.js
这是我无法弄清楚如何在 localhost:3000/projects/some-id/
的路径前添加问题的地方
<Link href={`/${router.pathname}/apple`}>
<a>Business name</a>
</Link>
如果我使用router.pathname
,我会得到/projects/[pid]/apple
,但缺少域名,如果我使用router.asPath
,我会得到正确的路径,但仍然缺少域名.我不知道这是否是正确的方法,因为我不应该将域名添加到 Link 的 href
.
对于 Nextjs 中的嵌套动态路由,您可以这样设置您的项目:
从 index.js
中的简单 link 开始
import Link from 'next/link';
export default function Index() {
return (
<section>
<h2>Index</h2>
<Link href="/projectA">
<a>Project A</a>
</Link>
</section>
);
}
进入[projectId].js
后,使用useRouter
获取当前参数并附加到下一条路线
import Link from 'next/link';
import { useRouter } from 'next/router';
export default function Project() {
const router = useRouter();
const { projectId } = router.query;
return (
<section>
<Link href={`/${projectId}/2`}>
<a>Project 2</a>
</Link>
</section>
);
}
您将如何处理嵌套动态路由并使用 Next.js Link 组件?
假设我有 2 个文件路径:
/pages/projects/index.js
<Link href={`/projects/${project.id}`} key={index}>
<a>Project Name</a>
</Link>
这会带我去 localhost:3000/projects/some-id/
和
/pages/projects/[pid]/index.js
这是我无法弄清楚如何在 localhost:3000/projects/some-id/
<Link href={`/${router.pathname}/apple`}>
<a>Business name</a>
</Link>
如果我使用router.pathname
,我会得到/projects/[pid]/apple
,但缺少域名,如果我使用router.asPath
,我会得到正确的路径,但仍然缺少域名.我不知道这是否是正确的方法,因为我不应该将域名添加到 Link 的 href
.
对于 Nextjs 中的嵌套动态路由,您可以这样设置您的项目:
从 index.js
中的简单 link 开始import Link from 'next/link';
export default function Index() {
return (
<section>
<h2>Index</h2>
<Link href="/projectA">
<a>Project A</a>
</Link>
</section>
);
}
进入[projectId].js
后,使用useRouter
获取当前参数并附加到下一条路线
import Link from 'next/link';
import { useRouter } from 'next/router';
export default function Project() {
const router = useRouter();
const { projectId } = router.query;
return (
<section>
<Link href={`/${projectId}/2`}>
<a>Project 2</a>
</Link>
</section>
);
}