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(),因為它使用了 TypeScriptnever型別。
版本歷史
| 版本 | 更改 |
|---|---|
v13.0.0 | notFound 已引入。 |
這有幫助嗎?