Next.js app目录下如何重定向至404 NotFound页面?
在Next.js 13 app目录(Server Components)中实现404页面重定向
在Next.js 13的app目录架构下,Server Components不再依赖getServerSideProps这类数据获取函数,实现404页面跳转可以通过以下两种方式:
方式一:使用notFound()函数
Next.js提供了notFound()函数,调用后会终止当前组件渲染,并自动触发全局404页面的展示,逻辑上和旧版的notFound: true返回值一致。
示例代码(动态路由app/[placeId]/page.js):
import { notFound } from 'next/navigation'; // 模拟数据获取函数 async function getPlace(placeId) { const res = await fetch(`https://api.example.com/places/${placeId}`); if (!res.ok) return []; return res.json(); } export default async function PlacePage({ params }) { const { placeId } = params; const places = await getPlace(placeId); // 数据为空时触发404 if (!places.length) { notFound(); } return ( <div> <h1>{places[0].name}</h1> {/* 页面其他内容 */} </div> ); }
方式二:返回<NotFound>组件
你也可以直接从next/navigation导入<NotFound>组件,在数据校验不通过时返回该组件,同样会触发404页面展示。
示例代码:
import { NotFound } from 'next/navigation'; async function getPlace(placeId) { const res = await fetch(`https://api.example.com/places/${placeId}`); if (!res.ok) return []; return res.json(); } export default async function PlacePage({ params }) { const { placeId } = params; const places = await getPlace(placeId); if (!places.length) { return <NotFound />; } return ( <div> <h1>{places[0].name}</h1> {/* 页面其他内容 */} </div> ); }
自定义404页面
如果需要展示自定义的404内容,只需在app目录下创建not-found.js文件,Next.js会自动使用这个组件作为404页面:
// app/not-found.js export default function CustomNotFound() { return ( <div style={{ textAlign: 'center', paddingTop: '50px' }}> <h2>404 - 页面不存在</h2> <p>抱歉,你访问的页面无法找到</p> </div> ); }
内容的提问来源于stack exchange,提问作者Youssouf Oumar
相关产品推荐
相关产品推荐

