usePathname
usePathname
是一个客户端组件钩子,让你可以读取当前 URL 的路径名。
- TypeScript
- JavaScript
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>
}
app/example-client-component.js
'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
或中间件
中使用重写时使用usePathname
,还必须使用useState
和useEffect
以避免水合不匹配错误。- 如果 Next.js 检测到你的项目中同时存在
app
和pages
目录,它将自动更新你的类型。
参数
const pathname = usePathname()
usePathname
不接受任何参数。
返回值
usePathname
返回当前 URL 路径名的字符串。例如:
URL | 返回值 |
---|---|
/ | '/' |
/dashboard | '/dashboard' |
/dashboard?v=2 | '/dashboard' |
/blog/hello-world | '/blog/hello-world' |
示例
响应路由更改执行某些操作
- TypeScript
- JavaScript
app/example-client-component.tsx
'use client'
import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
// 在这里执行某些操作...
}, [pathname, searchParams])
}
app/example-client-component.js
'use client'
import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
// 在这里执行某些操作...
}, [pathname, searchParams])
}
版本 | 更改 |
---|---|
v13.0.0 | 引入了 usePathname 。 |