Skip to main content

not-found.js

notFound 函数在路由段内抛出时,未找到的文件用于渲染 UI。除了提供自定义 UI 之外,Next.js 还将针对流式响应返回 200 HTTP 状态代码,针对非流式响应返回 404

¥The not-found file is used to render UI when the notFound function is thrown within a route segment. Along with serving a custom UI, Next.js will return a 200 HTTP status code for streamed responses, and 404 for non-streamed responses.

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>
)
}
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。

¥Good to know: In addition to catching expected notFound() errors, the root app/not-found.js file also handles any unmatched URLs for your whole application. This means users that visit a URL that is not handled by your app will be shown the UI exported by the app/not-found.js file.

属性

¥Props

not-found.js 组件不接受任何 props。

¥not-found.js components do not accept any props.

数据获取

¥Data Fetching

默认情况下,not-found 是服务器组件。你可以将其标记为 async 以获取并显示数据:

¥By default, not-found is a Server Component. You can mark it as async to fetch and display data:

import Link from 'next/link'
import { headers } from 'next/headers'

export default async function NotFound() {
const headersList = 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>
)
}
import Link from 'next/link'
import { headers } from 'next/headers'

export default async function NotFound() {
const headersList = 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 这样的客户端组件钩子来根据路径显示内容,则必须改为在客户端获取数据。

¥If you need to use Client Component hooks like usePathname to display content based on the path, you must fetch data on the client-side instead.

版本历史

¥Version History

版本变化
v13.3.0app/not-found 处理全局不匹配的 URL。
v13.0.0not-found 推出。