Skip to content

notFound

notFound 函数允许你在路由段内渲染 not-found file 以及注入 <meta name="robots" content="noindex" /> 标签。

¥The notFound function allows you to render the not-found file within a route segment as well as inject a <meta name="robots" content="noindex" /> tag.

notFound()

调用 notFound() 函数会引发 NEXT_NOT_FOUND 错误并终止引发该错误的路由段的渲染。指定 未找到文件 允许你通过在段内渲染 Not Found UI 来优雅地处理此类错误。

¥Invoking the notFound() function throws a NEXT_NOT_FOUND error and terminates rendering of the route segment in which it was thrown. Specifying a not-found file allows you to gracefully handle such errors by rendering a Not Found UI within the segment.

jsx
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((await params).id)

  if (!user) {
    notFound()
  }

  // ...
}

需要了解:由于使用 TypeScript never 类型,notFound() 不要求你使用 return notFound()

¥Good to know: notFound() does not require you to use return notFound() due to using the TypeScript never type.

版本历史

¥Version History

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

Next.js v15.2 中文网 - 粤ICP备13048890号