notFound

notFound 函数允许您在路由段内渲染 not-found 文件,并自动注入 <meta name="robots" content="noindex" /> 标签。

notFound()

调用 notFound() 函数会抛出 NEXT_NOT_FOUND 错误并终止当前路由段的渲染。通过定义 not-found 文件,您可以在该路由段内优雅地显示未找到页面 (Not Found UI)。

app/user/[id]/page.js
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 user = await fetchUser(params.id)

  if (!user) {
    notFound()
  }

  // ...
}

须知:由于使用了 TypeScript 的 never 类型,调用 notFound() 时无需写成 return notFound()

版本历史

版本变更说明
v13.0.0引入 notFound 功能。

On this page