Next.js 13中自定义not-found.jsx无法覆盖默认404页面问题
Next.js 13 app目录自定义404页面不生效的排查与解决
可能的原因及解决步骤:
- 文件名或扩展名问题:确保文件名是
not-found.js或not-found.tsx,优先使用官方推荐的扩展名,避免拼写错误(比如写成驼峰式NotFound.jsx,Next.js要求全小写加短横线命名)。 - 文件位置错误:确认
not-found.jsx放在app目录根路径下(即/app/not-found.jsx),而非子路由目录中。 - 动态路由拦截:如果项目存在
app/[...slug]/page.jsx这类兜底动态路由,所有未匹配的路由会被该页面捕获,不会自动触发自定义404。此时需要在动态路由的page.jsx中主动调用notFound()函数:import { notFound } from 'next/navigation'; export default function CatchAllPage({ params }) { // 校验路由是否合法,不合法则触发404 if (!isValidRoute(params.slug)) { notFound(); } // 正常页面逻辑 return <div>...</div>; } - 缓存或开发服务器问题:重启Next.js开发服务器(重新执行
npm run dev),同时清除浏览器缓存,避免旧资源干扰页面更新。 - 代码语法问题:你的代码中使用了原生HTML的
class属性,React中需改为className,否则样式会失效(虽不影响页面触发,但会导致样式丢失)。
修改后的not-found.jsx代码:
import React from "react"; function NotFound() { return ( <main className="grid min-h-full place-items-center bg-white px-6 py-24 sm:py-32 lg:px-8"> <div className="text-center"> <p className="text-base font-semibold text-indigo-600">404</p> <h1 className="mt-4 text-3xl font-bold tracking-tight text-gray-900 sm:text-5xl"> Page not found </h1> <p className="mt-6 text-base leading-7 text-gray-600"> Sorry, we couldn’t find the page you’re looking for. </p> <div className="mt-10 flex items-center justify-center gap-x-6"> <a href="/" className="rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600" > Go back home </a> <a href="/contact" className="text-sm font-semibold text-gray-900"> Contact support <span aria-hidden="true">→</span> </a> </div> </div> </main> ); } export default NotFound;
内容的提问来源于stack exchange,提问作者Mohammed Bekele
相关产品推荐
相关产品推荐

