useSelectedLayoutSegments
useSelectedLayoutSegments
是一个客户端组件钩子,可让你读取调用它的布局下方的活动路由段。
¥useSelectedLayoutSegments
is a Client Component hook that lets you read the active route segments below the Layout it is called from.
它对于在需要了解活动子段(例如面包屑)的父布局中创建 UI 非常有用。
¥It is useful for creating UI in parent Layouts that need knowledge of active child segments such as breadcrumbs.
'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>
)
}
'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>
)
}
很高兴知道:
¥Good to know:
由于
useSelectedLayoutSegments
是 客户端组件 钩子,并且布局默认为 服务器组件,因此通常通过导入到布局中的客户端组件来调用useSelectedLayoutSegments
。¥Since
useSelectedLayoutSegments
is a Client Component hook, and Layouts are Server Components by default,useSelectedLayoutSegments
is usually called via a Client Component that is imported into a Layout.返回的段包括 路由组,你可能不希望将其包含在 UI 中。你可以使用
filter()
数组方法删除以括号开头的项目。¥The returned segments include Route Groups, which you might not want to be included in your UI. You can use the
filter()
array method to remove items that start with a bracket.
参数
¥Parameters
const segments = useSelectedLayoutSegments(parallelRoutesKey?: string)
useSelectedLayoutSegments
可选择接受 parallelRoutesKey
,它允许你读取该槽内的活动航路段。
¥useSelectedLayoutSegments
optionally accepts a parallelRoutesKey
, which allows you to read the active route segment within that slot.
返回
¥Returns
useSelectedLayoutSegments
返回一个字符串数组,其中包含调用钩子的布局下一级的活动段。或者如果不存在则为空数组。
¥useSelectedLayoutSegments
returns an array of strings containing the active segments one level down from the layout the hook was called from. Or an empty array if none exist.
例如,给定下面的布局和 URL,返回的段将是:
¥For example, given the Layouts and URLs below, the returned segments would be:
布局 | 访问过的网址 | 返回的段 |
---|---|---|
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 History
版本 | 变化 |
---|---|
v13.0.0 | useSelectedLayoutSegments 推出。 |