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 包中),然后根据当前状态重新渲染。
须知:
- 不支持在服务端组件 (Server Component) 中读取当前 URL。此设计是为了在页面导航时保持布局状态。
- 兼容性模式:
- 当渲染回退路由 (fallback route) 或
pages目录页面被 Next.js 自动静态优化 (automatically statically optimized) 且路由未就绪时,usePathname可能返回null。- 如果检测到项目中同时存在
app和pages目录,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])
}'use client'
import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
// 在此执行操作...
}, [pathname, searchParams])
}| 版本 | 变更 |
|---|---|
v13.0.0 | 引入 usePathname。 |