推荐答案
在 Next.js 中,创建 404 页面非常简单。你只需要在 pages 目录下创建一个名为 404.js 或 404.tsx 的文件,Next.js 会自动将其识别为 404 页面。当用户访问一个不存在的路由时,Next.js 会自动渲染这个页面。
// pages/404.js
export default function Custom404() {
return <h1>404 - Page Not Found</h1>;
}本题详细解读
1. 404 页面的自动识别
Next.js 框架会自动识别 pages 目录下的 404.js 或 404.tsx 文件作为 404 页面。这意味着你不需要手动配置路由或处理逻辑来显示 404 页面,Next.js 会在用户访问不存在的路由时自动渲染这个页面。
2. 自定义 404 页面
你可以根据需要自定义 404 页面的内容和样式。例如,你可以在 404 页面中添加导航链接、图片或其他交互元素,以提升用户体验。
// www.javascriptcn.com code example
// pages/404.js
import Link from 'next/link';
export default function Custom404() {
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
<Link href="/">
<a>Go back to the homepage</a>
</Link>
</div>
);
}3. 404 页面的 SEO 优化
为了优化 404 页面的 SEO,你可以在页面中添加 <Head> 组件来设置页面的标题和元数据。
// www.javascriptcn.com code example
// pages/404.js
import Head from 'next/head';
import Link from 'next/link';
export default function Custom404() {
return (
<>
<Head>
<title>404 - Page Not Found</title>
<meta name="description" content="The page you are looking for does not exist." />
</Head>
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
<Link href="/">
<a>Go back to the homepage</a>
</Link>
</div>
</>
);
}4. 404 页面的国际化
如果你的应用支持多语言,你可以在 404 页面中使用 next-i18next 或其他国际化库来实现多语言支持。
// www.javascriptcn.com code example
// pages/404.js
import { useTranslation } from 'next-i18next';
import Link from 'next/link';
export default function Custom404() {
const { t } = useTranslation('common');
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>{t('404-title')}</h1>
<p>{t('404-message')}</p>
<Link href="/">
<a>{t('go-back-home')}</a>
</Link>
</div>
);
}通过以上方式,你可以在 Next.js 中轻松创建并自定义 404 页面,以满足不同的需求。