useSelectedLayoutSegments

useSelectedLayoutSegments 是一個客戶端元件 (Client Component) 鉤子,可讓您讀取從中呼叫此鉤子的佈局 (Layout) 下方的當前路由區段 (segments)。

這對於需要在父佈局中建立了解子區段狀態的 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 返回一個字串陣列,包含從呼叫此鉤子的佈局往下一個層級的有效區段。如果不存在則返回空陣列。

例如,根據以下佈局和訪問的 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 功能。

On this page