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>
}
'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 包中),然后根据当前状态重新渲染。

须知:

参数

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])
}
'use client'

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

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