跳到内容

notFound

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

notFound()

调用 notFound() 函数会抛出一个 NEXT_HTTP_ERROR_FALLBACK;404 错误,并终止其所在的路由段的渲染。指定一个 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 { id } = await params
  const user = await fetchUser(id)
 
  if (!user) {
    notFound()
  }
 
  // ...
}

须知notFound() 不需要你使用 return notFound(),因为它使用了 TypeScript never 类型。

版本历史

版本更改
v13.0.0notFound 已引入。