跳到内容
API 参考函数useSelectedLayoutSegments

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.0useSelectedLayoutSegments 已引入。