notFound
notFound
函数允许你在路由段中渲染 not-found file
,并注入 <meta name="robots" content="noindex" />
标签。
notFound()
调用 notFound()
函数会抛出一个 NEXT_HTTP_ERROR_FALLBACK;404
错误,并终止渲染抛出该错误的路由段。指定一个 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 { id } = await params
const user = await fetchUser(id)
if (!user) {
notFound()
}
// ...
}
须知:由于使用了 TypeScript
never
类型,notFound()
不需要你使用return notFound()
。
版本历史
版本 | 变更 |
---|---|
v13.0.0 | 引入了 notFound 。 |
这有帮助吗?