usePathname
usePathname 是一个**客户端组件**钩子,让你读取当前 URL 的**路径名**。
须知:当启用
cacheComponents时,如果你的路由有动态参数,usePathname可能需要一个Suspense边界包裹。如果你使用generateStaticParams,Suspense边界是可选的。
'use client'
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p>
}usePathname 有意地要求使用 客户端组件。重要的是要注意客户端组件并非一种反优化。它们是 服务器组件 架构不可或缺的一部分。
例如,一个带有 usePathname 的客户端组件会在初始页面加载时渲染成 HTML。当导航到新路由时,此组件不需要重新获取。相反,组件只需下载一次(在客户端 JavaScript 包中),并根据当前状态重新渲染。
须知:
与 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' |
示例
响应路由变化执行操作
'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.config 或 Proxy 进行重写而访问的,浏览器 URL 可能会有所不同,并且 usePathname() 将在客户端读取重写后的路径名。
为避免水合不匹配,请设计 UI,使只有一小部分独立的部分依赖于客户端路径名。在服务器上渲染稳定的回退,并在挂载后更新该部分。
'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。 |
这有帮助吗?