useSelectedLayoutSegments
useSelectedLayoutSegments
是一個客戶端元件 (Client Component) 鉤子,可讓你讀取呼叫它的 Layout 下方的當前路由區段。
這對於需要在父層 Layout 中建立了解子路由區段狀態的 UI (例如麵包屑導航) 非常有用。
須知事項:
- 由於
useSelectedLayoutSegments
是一個客戶端元件 (Client Component) 鉤子,而 Layout 預設是伺服器元件 (Server Components),所以通常會透過導入到 Layout 中的客戶端元件來呼叫useSelectedLayoutSegments
。- 返回的區段包含路由群組 (Route Groups),你可能不希望這些內容出現在 UI 中。可以使用
filter()
陣列方法來移除以括號開頭的項目。
參數
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 功能。 |