notFound
notFound 函数的 API 参考。
notFound 函数抛出一个错误,从而渲染 not-found UI。它可用于处理应用中缺失的资源。你可以使用 not-found.js 文件自定义该 UI。
调用 notFound() 会抛出 NEXT_HTTP_ERROR_FALLBACK;404 错误,并终止抛出它的路由段的渲染。Next.js 还会注入 <meta name="robots" content="noindex" /> 标签,使该页面不被索引。由于它通过抛错来工作,请在渲染路径中调用它:组件,或组件 await 的函数。如果调用遗留在未 await 的 promise 中,它会在无人捕获的地方抛出,且不会渲染 not-found UI(在开发环境中服务端会记录 ⨯ unhandledRejection: NEXT_HTTP_ERROR_FALLBACK;404)。
notFound() 可以在 Server Components、Server Functions 和 Route Handlers 中调用。
import { notFound } from 'next/navigation'
async function fetchUser(id: string) {
const res = await fetch('https://...')
if (!res.ok) return undefined
return res.json()
}
export default async function Profile({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
const user = await fetchUser(id)
if (!user) {
notFound()
}
// ...
}import { notFound } from 'next/navigation'
async function fetchUser(id) {
const res = await fetch('https://...')
if (!res.ok) return undefined
return res.json()
}
export default async function Profile({ params }) {
const { id } = await params
const user = await fetchUser(id)
if (!user) {
notFound()
}
// ...
}小知识#
你无需编写 return notFound()。直接调用即可,因为它会抛出异常从而停止函数执行。TypeScript 通过其 never 返回类型理解这一点,因此你先前检查过的值在之后仍保持类型收窄:
// fetchUser 解析为用户对象,或 undefined
const user = await fetchUser(id)
if (!user) {
notFound()
}
// 此处 user 已定义
return <Profile user={user} />与任何异常一样,它会沿调用栈向上传播,直到被捕获。在该调用周围加上 try/catch 会抑制它,not-found UI 就不会渲染。如果你需要在调用附近捕获错误,请使用 unstable_rethrow 先让该中断通过。
示例#
在流式渲染开始后调用 notFound()#
要在数据加载期间保持页面外壳和加载 UI 可见,请将存在性检查放在被 <Suspense> 包裹的组件内,而不要阻塞整个路由。进行检查的惯用位置是数据访问函数本身,由需要该数据的组件 await:
import { Suspense } from 'react'
import Link from 'next/link'
import { notFound } from 'next/navigation'
async function getPost(slug: string) {
const res = await fetch(`https://api.example.com/posts/${slug}`)
if (res.status === 404) {
notFound()
}
if (!res.ok) {
throw new Error(`Failed to load post: ${res.status}`)
}
return res.json()
}
async function Article({ slug }: { slug: string }) {
const post = await getPost(slug)
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
</article>
)
}
export default async function PostPage({ params }: PageProps<'/blog/[slug]'>) {
const { slug } = await params
return (
<section>
<Link href="/blog">Blog</Link>
<Suspense fallback={<p>Loading...</p>}>
<Article slug={slug} />
</Suspense>
</section>
)
}import { Suspense } from 'react'
import Link from 'next/link'
import { notFound } from 'next/navigation'
async function getPost(slug) {
const res = await fetch(`https://api.example.com/posts/${slug}`)
if (res.status === 404) {
notFound()
}
if (!res.ok) {
throw new Error(`Failed to load post: ${res.status}`)
}
return res.json()
}
async function Article({ slug }) {
const post = await getPost(slug)
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
</article>
)
}
export default async function PostPage({ params }) {
const { slug } = await params
return (
<section>
<Link href="/blog">Blog</Link>
<Suspense fallback={<p>Loading...</p>}>
<Article slug={slug} />
</Suspense>
</section>
)
}当文章不存在时,getPost 调用 notFound(),从而抛出异常。由于这发生在渲染期间,异常会传播到最近的 not-found 边界,由它渲染以替代流式渲染进来的内容,即使页面外壳已经发送。
在路由旁添加 not-found.tsx 来定义该 UI。如果没有,则渲染最近的父级 not-found 边界,最终回退到 Next.js 默认的 404 页面:
export default function NotFound() {
return (
<section>
<h1>Post not found</h1>
<p>The post you're looking for doesn't exist.</p>
</section>
)
}export default function NotFound() {
return (
<section>
<h1>Post not found</h1>
<p>The post you're looking for doesn't exist.</p>
</section>
)
}响应在 notFound() 运行之前就已从 <Suspense> 边界开始流式渲染,因此保持 200 状态码。Next.js 会添加 noindex 标签。
notFound() 如果在响应开始之前运行(包括预渲染期间),会返回 404。请参阅状态码。
从 Route Handler 返回 404#
notFound() 同样可在 Route Handler 中使用,向调用方返回 404。
import { NextResponse } from 'next/server'
import { notFound } from 'next/navigation'
export async function GET(
request: Request,
{ params }: RouteContext<'/api/posts/[slug]'>
) {
const { slug } = await params
const res = await fetch(`https://api.example.com/posts/${slug}`)
if (!res.ok) {
notFound()
}
return NextResponse.json(await res.json())
}import { NextResponse } from 'next/server'
import { notFound } from 'next/navigation'
export async function GET(request, { params }) {
const { slug } = await params
const res = await fetch(`https://api.example.com/posts/${slug}`)
if (!res.ok) {
notFound()
}
return NextResponse.json(await res.json())
}版本历史#
| 版本 | 变更 |
|---|---|
v13.0.0 | 引入 notFound。 |