usePathname
usePathname
是一个 客户端组件 hook,允许你读取当前 URL 的 路径名。
usePathname
有意要求使用 客户端组件。需要注意的是,客户端组件并不是一种优化上的缺陷。它们是 服务端组件 架构的重要组成部分。
例如,带有 usePathname
的客户端组件在初始页面加载时会被渲染成 HTML。当导航到新路由时,这个组件不需要重新获取。相反,该组件在客户端 JavaScript 包中下载一次,并根据当前状态重新渲染。
值得注意的是:
- 从 服务端组件 中读取当前 URL 是不支持的。这一设计是有意为之,以支持布局状态在页面导航之间保持不变。
- 兼容模式:
usePathname
在渲染 回退路由 或当 pages
目录页面被 Next.js 自动静态优化 并且路由器未就绪时,可能返回 null
。
- Next.js 会自动更新你的类型,如果它检测到你的项目中同时存在
app
和 pages
目录。
usePathname
不接受任何参数。
usePathname
返回当前 URL 路径名的字符串。例如:
URL | 返回值 |
---|
/ | '/' |
/dashboard | '/dashboard' |
/dashboard?v=2 | '/dashboard' |
/blog/hello-world | '/blog/hello-world' |
版本 | 变更 |
---|
v13.0.0 | usePathname 引入。 |