N Next.js 中文
原文 ↗

useSelectedLayoutSegments

useSelectedLayoutSegments Hook 的 API 参考。

更新于 2026-08-21Next.js 16.4.6

useSelectedLayoutSegments 是一个客户端组件 Hook,用于读取调用它的 Layout 下方的活动路由段。

它适用于在父 Layout 中创建需要了解活动子段(例如面包屑)的 UI。

TypeScript

app/example-client-component.tsxtsx
'use client'

import { useSelectedLayoutSegments } from 'next/navigation'

export default function ExampleClientComponent() {
  const segments = useSelectedLayoutSegments()

  return (
    <ul>
      {segments.map((segment, index) => (
        <li key={index}>{segment}</li>
      ))}
    </ul>
  )
}

JavaScript

app/example-client-component.jsjsx
'use client'

import { useSelectedLayoutSegments } from 'next/navigation'

export default function ExampleClientComponent() {
  const segments = useSelectedLayoutSegments()

  return (
    <ul>
      {segments.map((segment, index) => (
        <li key={index}>{segment}</li>
      ))}
    </ul>
  )
}

须知:

由于 useSelectedLayoutSegments 是一个客户端组件 Hook,而 Layout 默认是服务器组件,因此 useSelectedLayoutSegments 通常通过导入到 Layout 中的客户端组件来调用。 返回的段包含路由组,你可能不希望它们出现在 UI 中。你可以使用 filter 数组方法来移除以方括号开头的项。 对于捕获所有路由,匹配的段会作为单个拼接字符串返回在数组中。例如,给定 app/blog/[...slug]/page.js,在访问 /blog/a/b/c 时从 app/layout.js 调用会返回 ['blog', 'a/b/c'],而不是 ['blog', 'a', 'b', 'c']。

参数

const segments = useSelectedLayoutSegments(parallelRouteKey?: string)

useSelectedLayoutSegments 可选地接受一个 parallelRouteKey,允许你读取该插槽内的活动路由段。

返回值

useSelectedLayoutSegments 返回一个字符串数组,包含调用该 Hook 的 Layout 下一层的活动段。如果不存在,则返回空数组。

例如,给定以下 Layout 和 URL,返回的段将是:

Layout 访问的 URL 返回的段
app/layout.js / []
app/layout.js /dashboard ['dashboard']
app/layout.js /dashboard/settings ['dashboard', 'settings']
app/dashboard/layout.js /dashboard []
app/dashboard/layout.js /dashboard/settings ['settings']

对于捕获所有路由([...slug]),所有匹配的路径段会作为单个拼接字符串返回在数组中:

Layout 访问的 URL 返回的段
app/layout.js /blog/a/b/c ['blog', 'a/b/c']
app/blog/layout.js /blog/a/b/c ['a/b/c']

行为

缓存组件

启用 cacheComponents 后,useSelectedLayoutSegments 可能需要一个 Suspense 边界。这取决于活动段能否在预渲染期间解析。

  • 静态路由以及带有 generateStaticParams 的路由:每个路由段(包括动态参数)在构建时都是已知的。活动段可以在预渲染期间解析,因此 useSelectedLayoutSegments 会在服务器上解析,不需要 Suspense 边界。
  • 动态参数未被 generateStaticParams 覆盖的路由:该参数是 回退参数,直到请求时才能确定。活动段无法在预渲染期间解析,因此 useSelectedLayoutSegments 会挂起。请将组件(或其父级)包裹在 Suspense 边界中,以便在预渲染期间渲染其回退内容;否则,构建将失败。

即使调用 useSelectedLayoutSegments 的组件本身是静态的,这一点也适用。例如,在父布局中渲染的面包屑组件,在其下方任何带有未知动态参数的页面上都会挂起。为了让布局的其余部分保持预渲染,请将调用 useSelectedLayoutSegments 的组件(或其父级)包裹在带有回退内容的 Suspense 边界中。

有关完整的修复方案和权衡,请参阅 Next.js encountered URL data in a Client Component outside of Suspense。

版本历史

版本 变更
v13.0.0 引入 useSelectedLayoutSegments。