usePathname
usePathname
是一个客户端组件钩子,可让你读取当前 URL 的 pathname。
app/example-client-component.tsx
'use client'
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p>
}
usePathname
有意要求使用客户端组件。重要的是要注意客户端组件并非反优化。它们是服务器组件架构不可或缺的一部分。
例如,带有 usePathname
的客户端组件将在初始页面加载时渲染到 HTML 中。当导航到新路由时,无需重新获取此组件。相反,组件下载一次(在客户端 JavaScript 包中),并根据当前状态重新渲染。
须知:
- 不支持从服务器组件读取当前 URL。此设计是有意为之,旨在支持跨页面导航保留布局状态。
- 兼容模式
- 当回退路由正在渲染时,或者当
pages
目录页面已被 Next.js 自动静态优化且路由器尚未就绪时,usePathname
可能会返回null
。- 在
next.config
或Middleware
中使用带有 rewrites 的usePathname
时,还必须使用useState
和useEffect
,以避免水合不匹配错误。- 如果 Next.js 检测到你的项目中同时存在
app
和pages
目录,它将自动更新你的类型。
参数
const pathname = usePathname()
usePathname
不接受任何参数。
返回值
usePathname
返回当前 URL 的 pathname 字符串。例如
URL | 返回值 |
---|---|
/ | '/' |
/dashboard | '/dashboard' |
/dashboard?v=2 | '/dashboard' |
/blog/hello-world | '/blog/hello-world' |
示例
对路由更改做出响应
app/example-client-component.tsx
'use client'
import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
// Do something here...
}, [pathname, searchParams])
}
版本 | 更改 |
---|---|
v13.0.0 | 引入 usePathname 。 |
这是否有帮助?