这是我的文件夹结构:
app
├── (app1)
│ └── ekko
│ ├── layout.tsx
│ ├── not-found.tsx
│ └── page.tsx
│
└── (admin)
│ └── admin
│ ├── layout.tsx
│ ├── not-found.tsx
│ └── page.tsx
│
└── layout.tsx
每个路由组都有
not-found.tsx
,当我访问错误的路径名时,例如/admin/whatever
,我希望它能够呈现 /admin/not-found.tsx
,但它却呈现默认的 404 页面。
我希望在导航到
/ekko/wrong-params
时获得指定的“未找到”页面
当用户点击 admi/错误参数时:
我想要当用户点击 ekko/wrong-params 时
然后显示这个未找到的页面:
当用户点击 admi/错误参数时:
not-found.tsx
文件捕获 notFound()
仅在一个段级别中抛出。
如果你在
notFound()
中执行/admin/page.tsx
,它将渲染/admin/not-found.tsx
// admin/page.tsx
import {notFound} from "next/navigation";
export default function AdminPage() {
const user = await getSession();
if (!user || user.role !== "ADMIN") notFound();
// ...
}
它不能捕获所有嵌套路由。
除了根
app/not-found.tsx
。除了在 notFound()
中捕获 app/page.tsx
呼叫外,它将用作从 [email protected] 开始的 404 请求的后备。您看到默认 404 而不是 not-found.tsx 文件的原因是,如果没有任何文件,Next.js 会在后台生成 app/not-found.js
。
您可以通过使用
[...name]
格式的 Catch All 路线来实现您的要求。只需将您的 */not-found.tsx
内容移至 */[...anyName]/page.tsx
,如下所示:
app
├── (app1)
│ └── ekko
│ ├── layout.tsx
│ ├── [...anyNotFound]/page.tsx
│ └── page.tsx
│
└── (admin)
│ └── admin
│ ├── layout.tsx
│ ├── [...catchAll]/page.tsx
│ └── page.tsx
│
└── layout.tsx
在捕获所有段中,您可以访问 URL。
// [...name]/page.tsx
interface Props {
params: {
name: string[]
}
}
export default function name({ params }: Props) {
return <div>The {params.name.join("/")} is not found</div>
}