前言
在 Next.js 项目中,当用户访问不存在的页面时,默认会显示一个简单的 404 页面。为了提供更好的用户体验,我们可以自定义 404 页面,使其与网站风格保持一致。
App Router 方式(推荐)
如果你使用的是 Next.js 13+ 的 App Router,只需在 app 目录下创建 not-found.tsx 文件:
// app/not-found.tsx
import Link from 'next/link';
export default function NotFound() {
return (
404
页面不存在
href="/"
className="mt-6 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors"
>
返回首页
);
}
Pages Router 方式
如果你使用的是传统的 Pages Router,则在 pages 目录下创建 404.tsx 文件:
// pages/404.tsx
import Link from 'next/link';
export default function Custom404() {
return (
404
页面不存在
返回首页
);
}
进阶技巧
1. 手动触发 404
在 App Router 中,你可以使用 notFound() 函数手动触发 404 页面:
import { notFound } from 'next/navigation';
export default async function Page({ params }: { params: { id: string } }) {
const data = await fetchData(params.id);
if (!data) {
notFound(); // 触发 404 页面
}
return
}
2. 嵌套路由的 404
你可以在特定路由段下创建 not-found.tsx,实现不同模块的自定义 404:
app/
├── not-found.tsx # 全局 404
├── blog/
│ └── not-found.tsx # /blog/* 的 404
└── admin/
└── not-found.tsx # /admin/* 的 404
3. 添加动画效果
可以结合 Framer Motion 等动画库,让 404 页面更加生动:
'use client';
import { motion } from 'framer-motion';
import Link from 'next/link';
export default function NotFound() {
return (
initial={{ scale: 0 }} animate={{ scale: 1 }} className="text-8xl font-bold" > 404
initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }} className="text-xl mt-4" > 页面走丢了...
initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.4 }} > 带我回家
);
}
总结
App Router:创建 app/not-found.tsx
Pages Router:创建 pages/404.tsx
使用 notFound() 函数可手动触发 404
支持嵌套路由级别的自定义 404 页面
自定义 404 页面不仅能提升用户体验,还能保持网站的整体风格一致性,是一个简单但重要的优化点。