Skip to content

usePathname

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

¥usePathname is a Client Component hook that lets you read the current URL's pathname.

需要了解:启用 cacheComponents 后,如果你的路由包含动态参数,则 usePathname 可能需要 Suspense 边界。如果你使用 generateStaticParams,则 Suspense 边界是可选的。

¥Good to know: When cacheComponents is enabled usePathname may require a Suspense boundary around it if your route has a dynamic param. If you use generateStaticParams the Suspense boundary is optional

tsx
'use client'

import { usePathname } from 'next/navigation'

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

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

¥usePathname intentionally requires using a Client Component. It's important to note Client Components are not a de-optimization. They are an integral part of the Server Components architecture.

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

¥For example, a Client Component with usePathname will be rendered into HTML on the initial page load. When navigating to a new route, this component does not need to be re-fetched. Instead, the component is downloaded once (in the client JavaScript bundle), and re-renders based on the current state.

需要了解:

¥Good to know:

  • 不支持从 服务器组件 读取当前 URL。此设计旨在支持跨页面导航保留布局状态。

    ¥Reading the current URL from a Server Component is not supported. This design is intentional to support layout state being preserved across page navigations.

  • 如果你的页面是静态预渲染的,并且你的应用在 next.config代理 文件中包含 rewrites,则使用 usePathname() 读取路径名可能会导致水合不匹配错误 - 因为初始值来自服务器,并且可能与路由后的实际浏览器路径名不匹配。请参阅我们的 example 以了解缓解此问题的方法。

    ¥If your page is being statically pre-rendered and your app has rewrites in next.config or a Proxy file, reading the pathname with usePathname() can result in hydration mismatch errors—because the initial value comes from the server and may not match the actual browser pathname after routing. See our example for a way to mitigate this issue.

Compatibility with Pages Router

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

¥If you have components that use usePathname and they are imported into routes within the Pages Router, be aware that usePathname may return null if the router is not yet initialized. This can occur in cases such as fallback routes or during Automatic Static Optimization in the Pages Router.

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

¥To enhance compatibility between routing systems, if your project contains both an app and a pages directory, Next.js will automatically adjust the return type of usePathname.

参数

¥Parameters

tsx
const pathname = usePathname()

usePathname 不带任何参数。

¥usePathname does not take any parameters.

返回

¥Returns

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

¥usePathname returns a string of the current URL's pathname. For example:

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

示例

¥Examples

响应路由变化做一些事情

¥Do something in response to a route change

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])
}

避免重写导致的 hydration 不匹配

¥Avoid hydration mismatch with rewrites

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

¥When a page is pre-rendered, the HTML is generated for the source pathname. If the page is then reached through a rewrite using next.config or Proxy, the browser URL may differ, and usePathname() will read the rewritten pathname on the client.

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

¥To avoid hydration mismatches, design the UI so that only a small, isolated part depends on the client pathname. Render a stable fallback on the server and update that part after mount.

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.0usePathname 已引入。