跳至內容

not-found.js

當路由區段中拋出 notFound 函式時,會使用 not-found 檔案來渲染 UI。除了提供自訂 UI 之外,Next.js 還會針對串流回應傳回 200 HTTP 狀態碼,而針對非串流回應則傳回 404

app/not-found.tsx
import Link from 'next/link'
 
export default function NotFound() {
  return (
    <div>
      <h2>Not Found</h2>
      <p>Could not find requested resource</p>
      <Link href="/">Return Home</Link>
    </div>
  )
}

注意事項:除了攔截預期的 notFound() 錯誤之外,根目錄 app/not-found.js 檔案也會處理整個應用程式中任何不符的 URL。這表示造訪應用程式未處理之 URL 的使用者,將會看到 app/not-found.js 檔案匯出的 UI。

屬性

not-found.js 元件不接受任何屬性。

資料擷取

預設情況下,not-found 是一個伺服器組件。您可以將其標記為 async 來擷取並顯示資料。

app/not-found.tsx
import Link from 'next/link'
import { headers } from 'next/headers'
 
export default async function NotFound() {
  const headersList = await headers()
  const domain = headersList.get('host')
  const data = await getSiteData(domain)
  return (
    <div>
      <h2>Not Found: {data.name}</h2>
      <p>Could not find requested resource</p>
      <p>
        View <Link href="/blog">all posts</Link>
      </p>
    </div>
  )
}

如果您需要使用像 usePathname 這樣的客戶端組件 hooks 來根據路徑顯示內容,則必須改在客戶端擷取資料。

版本歷史紀錄

版本變更
v13.3.0根目錄 app/not-found 處理全域不匹配的 URL。
v13.0.0引入 not-found