useSelectedLayoutSegments
useSelectedLayoutSegments Hook 的 API 参考。
useSelectedLayoutSegments 是一个 Client Component Hook,可让你读取调用它的 Layout 下方的活动路由段。
它适用于在父级 Layout 中创建需要了解活动子段信息的 UI,例如面包屑导航。
app/example-client-component.tsx
'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>
)
}app/example-client-component.js
'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是一个 Client Component Hook,而 Layout 默认是 Server Components,因此useSelectedLayoutSegments通常通过导入到 Layout 中的 Client Component 来调用。- 返回的段中包含 Route Groups,你可能不希望它们出现在 UI 中。你可以使用
filter数组方法来移除以方括号开头的项。- 对于 catch-all 路由,匹配的段会作为单个连接字符串返回在数组中。例如,给定
app/blog/[...slug]/page.js,从app/layout.js调用并在访问/blog/a/b/c时,返回['blog', 'a/b/c'],而不是['blog', 'a', 'b', 'c']。
参数#
tsx
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'] |
对于 catch-all 路由([...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'] |
行为#
Cache Components#
当 cacheComponents 启用时,useSelectedLayoutSegments 可能需要一个 Suspense 边界。这取决于活动段是否能在预渲染期间解析。
- 静态路由以及带有
generateStaticParams的路由:每个路由段(包括动态参数)在构建时都是已知的。活动段可以在预渲染期间解析,因此useSelectedLayoutSegments在服务端解析,不需要Suspense边界。 - 带有未被
generateStaticParams覆盖的动态参数的路由:该参数是一个回退参数,直到请求时才知道。活动段无法在预渲染期间解析,因此useSelectedLayoutSegments会挂起(suspend)。请将该组件(或其父组件)包裹在Suspense边界中,以便其 fallback 能在预渲染期间渲染;否则构建会失败。
即使调用 useSelectedLayoutSegments 的组件本身是静态的,这也适用。例如,在父级 layout 中渲染的面包屑组件,在其下方任何具有未知动态参数的页面上都会挂起。为了保持 layout 的其余部分被预渲染,请将调用 useSelectedLayoutSegments 的组件(或其父组件)包裹在带有 fallback 的 Suspense 边界中。
有关完整的修复选项和取舍,请参阅 Next.js 在 Suspense 之外的 Client Component 中遇到 URL 数据。
版本历史#
| 版本 | 变更 |
|---|---|
v13.0.0 | 引入 useSelectedLayoutSegments。 |