跳到主要内容

useSelectedLayoutSegments

useSelectedLayoutSegments 是一个客户端组件钩子,让你可以读取调用它的布局下方的活动路由段。

它对于在需要了解活动子段(如面包屑导航)的父布局中创建 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>
)
}

提示

  • 由于 useSelectedLayoutSegments 是一个 客户端组件 钩子,而布局默认是 服务端组件useSelectedLayoutSegments 通常通过导入到布局中的客户端组件来调用。
  • 返回的段包括 路由组,你可能不希望将它们包含在你的 UI 中。你可以使用 filter 数组方法来移除以括号开头的项目。

参数

const segments = useSelectedLayoutSegments(parallelRoutesKey?: string)

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

返回值

useSelectedLayoutSegments 返回一个字符串数组,包含从调用钩子的布局向下一个级别的活动段。如果不存在则返回空数组。

例如,给定下面的布局和 URL,返回的段将是:

布局访问的 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']

版本历史

版本更改
v13.0.0引入了 useSelectedLayoutSegments