跳到主要內容

notFound

notFound 函式可讓您在路由區段中渲染 not-found 檔案,並注入 <meta name="robots" content="noindex" /> 標籤。

notFound()

調用 notFound() 函式會拋出 NEXT_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((await params).id)
 
  if (!user) {
    notFound()
  }
 
  // ...
}

要知道的好處:由於使用了 TypeScript never 類型,notFound() 不需要您使用 return notFound()

版本歷史

版本變更
v13.0.0引入了 notFound