【问题标题】:Next.js prepending current path for nested dynamic routes in Link componentsNext.js 为 Link 组件中的嵌套动态路由添加当前路径
【发布时间】:2021-11-04 21:12:53
【问题描述】:

您将如何处理嵌套的动态路由和使用 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中。

【问题讨论】:

  • 所以你想在你的router.pathname 中有projects,我明白了吗?
  • 有点不清楚。您对/pages/projects/index.js/pages/projects/[pid]/index.js 有疑问或“缺少域名”是问题所在?
  • @RyanLe 嗨,对,因为它嵌套在动态路由 [pid] 中。我希望能够正确地做到这一点,在 /pages/projects/[pid]/index.js 中添加当前 URL,这样我就可以轻松地在之后添加企业名称路径。从你上次帮助我开始,我也希望能够做布局组件,但我正在尝试找出正确的路径名
  • @RGog 好吧,我想弄清楚如何处理动态和嵌套路由,因为无论我在做什么都没有让当前路由预先设置,所以我可以做类似/apple在下一页的末尾
  • 你为什么不把“project”然后你的[pid]放在后面?

标签: javascript react-router next.js router


【解决方案1】:

对于 Nextjs 中的嵌套动态路由,您可以像这样设置您的项目:

从 index.js 中的一个简单链接开始

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>
  );
}

Working example

【讨论】:

  • 哦,这很简单。为什么我没有想到呢?使用 router.query... 我认为这是关键。再次感谢!
  • 很高兴它有帮助!如果您需要我的帮助,请告诉我。
猜你喜欢
  • 2023-03-09
  • 2021-01-29
  • 2021-12-02
  • 2022-07-29
  • 2021-09-28
  • 2020-09-22
  • 2021-11-04
  • 1970-01-01
  • 2019-04-01
相关资源
最近更新 更多