【问题标题】:Unpredictable routing in nextjs when routing from a nested route从嵌套路由路由时,nextjs 中的不可预测路由
【发布时间】:2021-08-16 14:10:43
【问题描述】:

我在 pages 文件夹中创建了一个名为 dashboard 的文件夹,其中包含以下文件:

  1. index.tsx
  2. customers.tsx
  3. invoice.tsx
  4. items.tsx

当用户路由到http://localhost:3000/dashboard 时,会呈现index.tsx 页面。但是,当我单击按钮并路由到发票或客户时,当我检查路由到 http://localhost:3000/customershttp://localhost:3000/invoices 而不是 http://localhost:3000/dashboard/customershttp://localhost:3000/dashboard/invoices 的 URL 时,我得到一个 404 page

但是当我尝试在 href 中为客户编写完整路线时:

//It will work after refreshing the page
<Link href='dashboard/customers'>
  <a>Customers</a>
</Link>

当我尝试将客户的任何路线路由到任何嵌套页面时,例如:

<Link href='dashboard/invoices'>
  <a>Customers</a>
</Link>
// I tend to get a 404 page

当我检查网址时,它执行了以下操作:http://localhost:3000/dashboard/dashboard/invoices 而不是 http://localhost:3000/dashboard/invoices

下面的按钮代码:

<Link href='/customers'>
  <a>Customers</a>
</Link>

<Link href='/invoices'>
  <a>Invoices</a>
</Link>

真的不知道自己做错了什么

【问题讨论】:

    标签: typescript next.js


    【解决方案1】:

    &lt;Link href='dashboard/invoices' /&gt; 是相对路径 - href='dashboard/invoices' 表示去/yourCurrentLocation/dashboard/invoices

    对于绝对路由,您必须在前面加上 /。这意味着它将始终相对于根目录进行路由。因此,您的代码应该是&lt;Link href='/dashboard/invoices' /&gt;

    【讨论】:

    • 无法避免感谢你,即使占位符告诉我不要这样做。
    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2022-07-24
    • 1970-01-01
    • 2019-01-12
    相关资源
    最近更新 更多