N Next.js 中文
原文 ↗

navigation

使用 navigation 函数将运行时工作延迟到用户导航时。

更新于 2026-10-15Next.js 16.4.6

调用 await navigation() 会使其下方的运行时工作排除在 App Shell 和按链接的预取之外。该工作会在用户导航时运行,而最近的 <Suspense> 边界的 fallback 会在预取的输出中渲染。

对于生成成本高且应等到导航时才处理的可复用内容,请使用 navigation()。静态预渲染仍会在其输出中包含该内容,因此它可能出现在静态预取中。

用法

该函数需要 Cache Components,没有它就会抛出错误。它适用于使用 Partial Prefetching 的路由,你可以全局启用,或通过采用 Partial Prefetching 逐个路由启用。

next.config.tsts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
}

export default nextConfig

启用 Partial Prefetching 后,Next.js 会在客户端导航之前和期间分阶段加载服务器渲染的输出。以下是该路由的导航阶段:

  1. 默认的 <Link> 会加载 App Shell,其中包含路由中不依赖 URL 的部分。
  2. 可选的 <Link prefetch={true}> 还可以加载依赖链接 URL 的内容。
  3. 当用户跟随该链接时,导航会渲染该路由的其余部分。

在运行时渲染期间,await navigation() 会使内容不包含在 App Shell 和按链接的预取中,因此它会在导航期间渲染。静态预渲染仍可包含该内容。

在未启用 Partial Prefetching 的情况下,navigation() 仍会为默认的 <Link> 延迟该内容,但 <Link prefetch={true}> 会获取整个路由(包括被延迟的内容),与导航时相同。

若要让内容不包含在 App Shell 中,但仍包含在按链接的预取中,请使用 prefetch()。

须知:

navigation() 延迟一个子树。若要在整个路由中要求静态 App Shell 和静态按链接预取,请使用 ensureStatic = 'prefetch'。有关完整示例,请参阅保持页面为静态。

navigation() 之上的所有内容都可以在 App Shell 或按链接的预取中渲染,而其下方的所有内容都会等待导航。延迟的作用范围仅限于 await 它的组件及其下方的树:同级分支保持其现有行为。将它放在要延迟的代码之上,并用 <Suspense> 包裹该组件:

TypeScript

app/post/[slug]/page.tsxtsx
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, navigation } from 'next/cache'

export default function Page({ params }: PageProps<'/post/[slug]'>) {
  return (
    <>
      <Suspense fallback={<p>Loading post...</p>}>
        <PostBody params={params} /> {/* in a per-link prefetch */}
      </Suspense>
      <Suspense fallback={<p>Loading comments...</p>}>
        {/* the fallback is in the prefetch, the comments are not */}
        <Comments params={params} />
      </Suspense>
    </>
  )
}

async function Comments({ params }: { params: Promise<{ slug: string }> }) {
  await navigation() // runtime work below renders on navigation
  const { slug } = await params
  const sort = (await cookies()).get('comment-sort')?.value ?? 'newest'
  const items = await getComments(slug, sort)
  return <CommentList items={items} />
}

async function getComments(slug: string, sort: string) {
  'use cache'
  cacheLife('hours')
  return db.comments.list({ slug, sort })
}

JavaScript

app/post/[slug]/page.jsjsx
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, navigation } from 'next/cache'

export default function Page({ params }) {
  return (
    <>
      <Suspense fallback={<p>Loading post...</p>}>
        <PostBody params={params} /> {/* in a per-link prefetch */}
      </Suspense>
      <Suspense fallback={<p>Loading comments...</p>}>
        {/* the fallback is in the prefetch, the comments are not */}
        <Comments params={params} />
      </Suspense>
    </>
  )
}

async function Comments({ params }) {
  await navigation() // runtime work below renders on navigation
  const { slug } = await params
  const sort = (await cookies()).get('comment-sort')?.value ?? 'newest'
  const items = await getComments(slug, sort)
  return <CommentList items={items} />
}

async function getComments(slug, sort) {
  'use cache'
  cacheLife('hours')
  return db.comments.list({ slug, sort })
}

评论按 slug 获取,因此预取它们需要按链接的预取。在该数据访问之前 await navigation() 会使它们不包含在预取中,因此它们会在用户导航时渲染。

slug 和 cookie 都在 navigation() 下方读取并作为参数传递,因此 getComments 按文章和排序顺序缓存,而不是按访客缓存。在被延迟的内容渲染时,URL 已解析完成,因此 params 在 navigation() 下方可用。

将该指令放在在其下方调用的函数上,就像这里的 getComments 那样。不允许在缓存作用域(例如 use cache 或 use cache: private)内 await navigation()。

navigation() 与 connection() 的区别

connection() 函数会等待真实请求。它会将后续代码排除在预渲染和预取之外,使该工作依赖于请求。

await navigation() 会将后续代码排除在路由预取之外。它在用户导航时解析,而不会使该工作依赖于请求。因此,在 await navigation() 之后调用的函数可以使用 "use cache" 并保持其缓存生命周期,而无需在预取期间生成结果。

当工作必须为真实请求运行时,使用 connection()。当工作可复用但应等到用户导航时再执行时,使用 navigation()。

何时使用

当其下方的内容生成成本高昂、且不应由预取生成时,使用 navigation()。

运行时 App Shell 和运行时按链接预取都不会执行该代码,因此其上游请求要等到用户导航时才会发出。

让内容保持不缓存也会使其不进入预取,但会放弃其缓存生命周期。

使用 navigation(),可以通过 use cache 缓存内容、为其设置生命周期,并将其推迟到导航时。为其设置 stale 时间为五分钟或更长,客户端路由器会在用户首次导航进入该路由后复用它。低于该值,较短的生命周期会使其不进入 App Shell,因此每次导航都会重新获取它。

保持路由的预取为静态

当对 cookies()、headers()、params 和 searchParams 的每次读取都位于 navigation() 之下时,预取会触发的预渲染无法产出超过构建时已生成的静态输出的内容,因此预取会改为从该输出中提供。以这种方式塑造路由是一种可选优化:静态响应可以缓存在 CDN 中,因此指向该路由的链接完全不消耗服务器 CPU。

app/feed/page.tsxtsx
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { navigation } from 'next/cache'

export default function Page() {
  return (
    <>
      <FeedHeader /> {/* static, and so is the whole prefetch */}
      <Suspense fallback={<p>Loading stories...</p>}>
        <Stories />
      </Suspense>
    </>
  )
}

async function Stories() {
  await navigation()
  const topic = (await cookies()).get('topic')?.value ?? 'all'
  return <StoryList items={await getStories(topic)} />
}

须知

  • 该函数对页面的初始加载没有影响。
  • 在 navigation() 之下读取 cookies() 或 headers() 不会使该路由的预取按请求进行渲染,因此它们仍可从静态输出中提供。这些访问会被忽略,因为它们在预取中同样无法解析。
  • 在 <Suspense> 边界之外调用会在开发环境中暴露 Instant Insight。完全预渲染的路由不受影响,但该洞察会指出:如果该路由之后需要运行时渲染,此调用会在没有回退内容的情况下推迟内容。
  • 在 use cache、use cache: private、unstable_cache()、after()、generateStaticParams 或客户端组件内部调用它会抛出错误。

参考

类型

function navigation(): Promise<void>

参数

  • 该函数不接受任何参数。

返回值

一个 Promise<void>。它并非供使用而设计。

版本历史

版本 变更
v16.4.0 引入 navigation,取代早期 canary 版本中使用的 unstable_navigation 名称。
  • 优化预取:解析按链接的 URL 数据、将会话数据包含在 App Shell 中,或将昂贵的工作推迟到后续导航阶段。
  • 保持页面静态:随着应用发生变化,保持选定路由的输出为静态。
  • prefetch:将运行时工作推迟到使用 prefetch 函数的按链接预取或导航时执行。
  • connection:connection 函数的 API 参考。
  • partialPrefetching:配置默认的链接预取行为,只获取每个路由的静态部分。