useSelectedLayoutSegment
useSelectedLayoutSegment hook 的 API 参考。
useSelectedLayoutSegment 是一个客户端组件 hook,可用于读取相对于调用它的 Layout 下一级的活动路由段。
它适用于导航 UI,例如父布局中根据活动子段改变样式的标签页。
TypeScript
'use client'
import { useSelectedLayoutSegment } from 'next/navigation'
export default function ExampleClientComponent() {
const segment = useSelectedLayoutSegment()
return <p>Active segment: {segment}</p>
}
JavaScript
'use client'
import { useSelectedLayoutSegment } from 'next/navigation'
export default function ExampleClientComponent() {
const segment = useSelectedLayoutSegment()
return <p>Active segment: {segment}</p>
}
须知:
- 由于
useSelectedLayoutSegment是一个客户端组件 hook,而 Layout 默认是服务器组件,因此useSelectedLayoutSegment通常通过导入到 Layout 中的客户端组件来调用。useSelectedLayoutSegment只返回下一级的段。要返回所有活动段,请参阅useSelectedLayoutSegments- 对于 catch-all 路由,匹配到的段会作为单个拼接字符串返回。例如,给定
app/blog/[...slug]/page.js,在访问/blog/a/b/c时从app/blog/layout.js调用会返回'a/b/c'。
参数
const segment = useSelectedLayoutSegment(parallelRouteKey?: string)
useSelectedLayoutSegment 可选地接受一个 parallelRouteKey,它允许你读取该插槽内的活动路由段。
返回值
useSelectedLayoutSegment 返回活动段的字符串,如果不存在则返回 null。
例如,给定以下 Layout 和 URL,返回的段将是:
| Layout | 访问的 URL | 返回的段 |
|---|---|---|
app/layout.js |
/ |
null |
app/layout.js |
/dashboard |
'dashboard' |
app/dashboard/layout.js |
/dashboard |
null |
app/dashboard/layout.js |
/dashboard/settings |
'settings' |
app/dashboard/layout.js |
/dashboard/analytics |
'analytics' |
app/dashboard/layout.js |
/dashboard/analytics/monthly |
'analytics' |
对于 catch-all 路由([...slug]),返回的段包含所有匹配的路径段,并拼接为单个字符串:
| Layout | 访问的 URL | 返回的段 |
|---|---|---|
app/blog/layout.js |
/blog/a/b/c |
'a/b/c' |
行为
缓存组件
启用 cacheComponents 后,useSelectedLayoutSegment 可能需要一个 Suspense 边界。这取决于活动段能否在预渲染期间解析。
- 静态路由以及带有
generateStaticParams的路由:每个路由段(包括动态参数)在构建时都是已知的。活动段可以在预渲染期间解析,因此useSelectedLayoutSegment会在服务器上解析,无需Suspense边界。 - 带有未被
generateStaticParams覆盖的动态参数的路由:该参数是一个 回退参数,直到请求时才能确定。活动段无法在预渲染期间解析,因此useSelectedLayoutSegment会挂起。将组件(或其父级)包裹在Suspense边界中,以便在预渲染期间渲染其回退内容;否则构建将失败。
即使调用 useSelectedLayoutSegment 的组件本身是静态的,这一点也同样适用。例如,在父级布局中渲染的标签栏,会在其下方任何具有未知动态参数的页面上挂起。为了让布局的其余部分保持预渲染状态,请将调用 useSelectedLayoutSegment 的组件(或其父级)包裹在带有回退内容的 Suspense 边界中。
有关完整的修复方案和权衡,请参阅 Next.js encountered URL data in a Client Component outside of Suspense。
示例
创建活动链接组件
你可以使用 useSelectedLayoutSegment 创建一个活动链接组件,根据活动段改变样式。例如,博客侧边栏中的精选文章列表:
TypeScript
'use client'
import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'
// This *client* component will be imported into a blog layout
export default function BlogNavLink({
slug,
children,
}: {
slug: string
children: React.ReactNode
}) {
// Navigating to `/blog/hello-world` will return 'hello-world'
// for the selected layout segment
const segment = useSelectedLayoutSegment()
const isActive = slug === segment
return (
<Link
href={`/blog/${slug}`}
// Change style depending on whether the link is active
style={{ fontWeight: isActive ? 'bold' : 'normal' }}
>
{children}
</Link>
)
}
// Import the Client Component into a parent Layout (Server Component)
import { BlogNavLink } from './blog-nav-link'
import getFeaturedPosts from './get-featured-posts'
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
const featuredPosts = await getFeaturedPosts()
return (
<div>
{featuredPosts.map((post) => (
<div key={post.id}>
<BlogNavLink slug={post.slug}>{post.title}</BlogNavLink>
</div>
))}
<div>{children}</div>
</div>
)
}
JavaScript
'use client'
import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'
// This *client* component will be imported into a blog layout
export default function BlogNavLink({ slug, children }) {
// Navigating to `/blog/hello-world` will return 'hello-world'
// for the selected layout segment
const segment = useSelectedLayoutSegment()
const isActive = slug === segment
return (
<Link
href={`/blog/${slug}`}
// Change style depending on whether the link is active
style={{ fontWeight: isActive ? 'bold' : 'normal' }}
>
{children}
</Link>
)
}
// Import the Client Component into a parent Layout (Server Component)
import { BlogNavLink } from './blog-nav-link'
import getFeaturedPosts from './get-featured-posts'
export default async function Layout({ children }) {
const featuredPosts = await getFeaturedPosts()
return (
<div>
{featuredPosts.map((post) => (
<div key={post.id}>
<BlogNavLink slug={post.slug}>{post.title}</BlogNavLink>
</div>
))}
<div>{children}</div>
</div>
)
}
版本历史
| 版本 | 变更 |
|---|---|
v13.0.0 |
引入 useSelectedLayoutSegment。 |