跳到内容
API 参考函数usePathname

usePathname

usePathname 是一个**客户端组件**钩子,让你读取当前 URL 的**路径名**。

须知:当启用 cacheComponents 时,如果你的路由有动态参数,usePathname 可能需要一个 Suspense 边界包裹。如果你使用 generateStaticParamsSuspense 边界是可选的。

app/example-client-component.tsx
'use client'
 
import { usePathname } from 'next/navigation'
 
export default function ExampleClientComponent() {
  const pathname = usePathname()
  return <p>Current pathname: {pathname}</p>
}

usePathname 有意地要求使用 客户端组件。重要的是要注意客户端组件并非一种反优化。它们是 服务器组件 架构不可或缺的一部分。

例如,一个带有 usePathname 的客户端组件会在初始页面加载时渲染成 HTML。当导航到新路由时,此组件不需要重新获取。相反,组件只需下载一次(在客户端 JavaScript 包中),并根据当前状态重新渲染。

须知:

  • 不支持从 服务器组件 读取当前 URL。这种设计是有意为之,旨在支持在页面导航时保留布局状态。
  • 如果你的页面是静态预渲染的,并且你的应用程序在 next.config 中有 重写代理 文件,使用 usePathname() 读取路径名可能会导致水合不匹配错误——因为初始值来自服务器,并且在路由后可能与实际的浏览器路径名不匹配。请参阅我们的示例以了解如何缓解此问题。
与 Pages Router 的兼容性

如果你的组件使用了 usePathname 并且它们被导入到 Pages Router 中的路由中,请注意,如果路由器尚未初始化,usePathname 可能会返回 null。这可能发生在 回退路由 或 Pages Router 中的 自动静态优化 等情况下。

为了增强路由系统之间的兼容性,如果你的项目同时包含 `app` 和 `pages` 目录,Next.js 会自动调整 `usePathname` 的返回类型。

参数

const pathname = usePathname()

usePathname 不接受任何参数。

返回

usePathname 返回当前 URL 路径名的字符串。例如:

URL返回值
/'/'
/dashboard'/dashboard'
/dashboard?v=2'/dashboard'
/blog/hello-world'/blog/hello-world'

示例

响应路由变化执行操作

app/example-client-component.tsx
'use client'
 
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
 
function ExampleClientComponent() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  useEffect(() => {
    // Do something here...
  }, [pathname, searchParams])
}

通过重写避免水合不匹配

当页面预渲染时,HTML 是为源路径名生成的。如果页面是通过使用 next.configProxy 进行重写而访问的,浏览器 URL 可能会有所不同,并且 usePathname() 将在客户端读取重写后的路径名。

为避免水合不匹配,请设计 UI,使只有一小部分独立的部分依赖于客户端路径名。在服务器上渲染稳定的回退,并在挂载后更新该部分。

app/example-client-component.tsx
'use client'
 
import { useEffect, useState } from 'react'
import { usePathname } from 'next/navigation'
 
export default function PathnameBadge() {
  const pathname = usePathname()
  const [clientPathname, setClientPathname] = useState('')
 
  useEffect(() => {
    setClientPathname(pathname)
  }, [pathname])
 
  return (
    <p>
      Current pathname: <span>{clientPathname}</span>
    </p>
  )
}
版本更改
v13.0.0引入了 usePathname