首页 > 解决方案 > 从嵌套路由路由时,nextjs 中的不可预测路由

问题描述

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

  1. 索引.tsx
  2. 客户.tsx
  3. 发票.tsx
  4. 物品.tsx

当用户路由到http://localhost:3000/dashboard页面index.tsx被渲染时。但是,当我单击一个按钮并路由到发票或客户404 page时,当我检查它路由到的 url 时,我得到一个http://localhost:3000/customers,而http://localhost:3000/invoices不是http://localhost:3000/dashboard/customersandhttp://localhost:3000/dashboard/invoices

但是,当我尝试在 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>

真的不知道我做错了什么

标签: typescriptnext.js

解决方案


<Link href='dashboard/invoices' />是一条相对路线——href='dashboard/invoices'去往的意思/yourCurrentLocation/dashboard/invoices

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


推荐阅读