NNext.js 中文网 GitHub

useSelectedLayoutSegment

useSelectedLayoutSegment hook 的 API 参考

useSelectedLayoutSegment 是一个 Client Component hook,可让你读取比调用它的 Layout 低一级的活动路由段。

它适用于导航 UI,例如父级 layout 中的标签页,其样式会根据活动的子路由段而变化。

app/example-client-component.tsx
'use client'

import { useSelectedLayoutSegment } from 'next/navigation'

export default function ExampleClientComponent() {
  const segment = useSelectedLayoutSegment()

  return <p>Active segment: {segment}</p>
}
app/example-client-component.js
'use client'

import { useSelectedLayoutSegment } from 'next/navigation'

export default function ExampleClientComponent() {
  const segment = useSelectedLayoutSegment()

  return <p>Active segment: {segment}</p>
}

小知识:

  • 由于 useSelectedLayoutSegment 是 Client Component hook,而 Layout 默认是 Server Component,因此 useSelectedLayoutSegment 通常通过导入到 Layout 中的 Client Component 来调用。
  • useSelectedLayoutSegment 只返回低一级的路由段。要返回所有活动段,请参阅 useSelectedLayoutSegments
  • 对于捕获所有(catch-all)路由,匹配的段会作为单个连接字符串返回。例如,给定 app/blog/[...slug]/page.js,从 app/blog/layout.js 调用并在访问 /blog/a/b/c 时返回 'a/b/c'。

参数#

tsx
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/dashboardnull
app/dashboard/layout.js/dashboard/settings'settings'
app/dashboard/layout.js/dashboard/analytics'analytics'
app/dashboard/layout.js/dashboard/analytics/monthly'analytics'

对于捕获所有路由([...slug]),返回的段包含所有匹配的路径段,并连接为单个字符串:

Layout访问的 URL返回的段
app/blog/layout.js/blog/a/b/c'a/b/c'

行为#

Cache Components#

当启用 cacheComponents 时,useSelectedLayoutSegment 可能需要 Suspense 边界。这取决于活动段是否可以在预渲染期间解析。

  • 静态路由和带有 generateStaticParams 的路由:每个路由段(包括动态参数)在构建时都是已知的。活动段可以在预渲染期间解析,因此 useSelectedLayoutSegment 在服务器上解析,无需 Suspense 边界。
  • 动态参数未被 generateStaticParams 覆盖的路由:该参数是直到请求时才已知的fallback 参数。活动段无法在预渲染期间解析,因此 useSelectedLayoutSegment 会挂起。请将组件(或其父级)包裹在 Suspense 边界中,以便其 fallback 可以在预渲染期间渲染;否则,构建会失败。

即使调用 useSelectedLayoutSegment 的组件本身是静态的,这也适用。例如,在父级 layout 中渲染的标签栏会在其下方任何具有未知动态参数的页面上挂起。为了让 layout 的其余部分保持预渲染,请将调用 useSelectedLayoutSegment 的组件(或其父级)包裹在带有 fallback 的 Suspense 边界中。

有关完整的修复选项和权衡,请参阅 Next.js 在 Suspense 之外的 Client Component 中遇到 URL 数据。

示例#

创建活动链接组件#

你可以使用 useSelectedLayoutSegment 创建一个活动链接组件,其样式根据活动段而变化。例如,博客侧边栏中的精选文章列表:

app/blog/blog-nav-link.tsx
'use client'

import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'

// 这个 *client* 组件将被导入到博客 layout 中
export default function BlogNavLink({
  slug,
  children,
}: {
  slug: string
  children: React.ReactNode
}) {
  // 导航到 `/blog/hello-world` 将返回 'hello-world'
  // 作为所选的 layout 段
  const segment = useSelectedLayoutSegment()
  const isActive = slug === segment

  return (
    <Link
      href={`/blog/${slug}`}
      // 根据链接是否处于活动状态更改样式
      style={{ fontWeight: isActive ? 'bold' : 'normal' }}
    >
      {children}
    </Link>
  )
}
app/blog/blog-nav-link.js
'use client'

import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'

// 这个 *client* 组件将被导入到博客 layout 中
export default function BlogNavLink({ slug, children }) {
  // 导航到 `/blog/hello-world` 将返回 'hello-world'
  // 作为所选的 layout 段
  const segment = useSelectedLayoutSegment()
  const isActive = slug === segment

  return (
    <Link
      href={`/blog/${slug}`}
      // 根据链接是否处于活动状态更改样式
      style={{ fontWeight: isActive ? 'bold' : 'normal' }}
    >
      {children}
    </Link>
  )
}
app/blog/layout.tsx
// 将 Client Component 导入父级 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>
  )
}
app/blog/layout.js
// 将 Client Component 导入父级 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。
Next.js 中文网