useSelectedLayoutSegments
useSelectedLayoutSegments 是一个 Client Component hook,它允许你读取调用它的 Layout 下方的活动路由段。
它对于在父 Layout 中创建需要了解活动子段的 UI 非常有用,例如面包屑导航。
app/example-client-component.tsx
TypeScript
'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,而 Layouts 默认是 Server Components,因此useSelectedLayoutSegments通常通过导入到 Layout 中的 Client Component 来调用。- 返回的段包含 Route Groups,你可能不希望将其包含在 UI 中。你可以使用
filter数组方法来移除以括号开头的项。
参数
const segments = useSelectedLayoutSegments(parallelRoutesKey?: string)useSelectedLayoutSegments 可选接受一个 parallelRoutesKey,允许你读取该插槽内的活动路由段。
返回值
useSelectedLayoutSegments 返回一个字符串数组,包含从调用 hook 的 layout 向下一级的活动段。如果不存在则返回空数组。
例如,给定以下 Layouts 和 URLs,返回的段将是:
| 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'] |
版本历史
| Version | Changes |
|---|---|
v13.0.0 | 引入 useSelectedLayoutSegments。 |