usePathname

usePathname 是一个 客户端组件 (Client Component) 钩子函数,用于读取当前 URL 的 路径名 (pathname)

'use client'

import { usePathname } from 'next/navigation'

export default function ExampleClientComponent() {
  const pathname = usePathname()
  return <p>Current pathname: {pathname}</p>
}

usePathname 特意设计为只能在 客户端组件 (Client Component) 中使用。需要特别注意的是,客户端组件并非性能劣化方案,而是 服务端组件 (Server Component) 架构的核心组成部分。

例如,一个使用了 usePathname 的客户端组件会在页面初始加载时渲染为 HTML。当导航到新路由时,该组件无需重新获取,而是只需下载一次(包含在客户端 JavaScript 包中),然后根据当前状态重新渲染。

须知

  • 不支持在 服务端组件 (Server Component) 中读取当前 URL。这一设计是为了确保布局状态在页面导航间得以保留。
  • 兼容性说明:
    • 当渲染 回退路由 (fallback route)pages 目录页面被 Next.js 自动静态优化 (automatically statically optimized) 且路由未就绪时,usePathname 可能返回 null
    • next.config 或 [中间件 (Middleware)](/docs/app/building-your-application/routing/middleware) 中使用重写规则时,必须同时使用 useStateuseEffect` 以避免水合不匹配错误。
    • 如果检测到项目中同时存在 apppages 目录,Next.js 会自动更新类型定义。

参数

const pathname = usePathname()

usePathname 不接受任何参数。

返回值

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

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

示例

响应路由变化执行操作

'use client'

import { usePathname, useSearchParams } from 'next/navigation'

function ExampleClientComponent() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  useEffect(() => {
    // 在此执行操作...
  }, [pathname, searchParams])
}
版本变更记录
v13.0.0首次引入 usePathname

On this page