useSelectedLayoutSegments

useSelectedLayoutSegments 是一個客戶端元件 (Client Component) 鉤子,可讓你讀取呼叫它的 Layout 下方的當前路由區段。

這對於需要在父層 Layout 中建立了解子路由區段狀態的 UI (例如麵包屑導航) 非常有用。

'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>
  )
}

須知事項:

參數

const segments = useSelectedLayoutSegments(parallelRoutesKey?: string)

useSelectedLayoutSegments 可選擇性接受一個 parallelRoutesKey 參數,允許你讀取該插槽中的當前路由區段。

返回值

useSelectedLayoutSegments 返回一個字串陣列,包含從呼叫該鉤子的 Layout 往下一個層級的路由區段。如果不存在則返回空陣列。

例如,根據下面的 Layouts 和訪問的 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']

版本歷史

版本變更內容
v13.0.0新增 useSelectedLayoutSegments 功能。

On this page