主题
usePathname
usePathname 是一个客户端组件钩子,可让你读取当前 URL 的路径名。
¥usePathname is a Client Component hook that lets you read the current URL's pathname.
tsx
'use client'
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p>
}usePathname 有意要求使用 客户端组件。重要的是要注意客户端组件并不是去优化。它们是 服务器组件 架构不可或缺的一部分。
¥usePathname intentionally requires using a Client Component. It's important to note Client Components are not a de-optimization. They are an integral part of the Server Components architecture.
例如,带有 usePathname 的客户端组件将在初始页面加载时渲染为 HTML。当导航到新路由时,不需要重新获取该组件。相反,组件会下载一次(在客户端 JavaScript 包中),然后根据当前状态重新渲染。
¥For example, a Client Component with usePathname will be rendered into HTML on the initial page load. When navigating to a new route, this component does not need to be re-fetched. Instead, the component is downloaded once (in the client JavaScript bundle), and re-renders based on the current state.
需要了解:
¥Good to know:
不支持从 服务器组件 读取当前 URL。此设计旨在支持跨页面导航保留布局状态。
¥Reading the current URL from a Server Component is not supported. This design is intentional to support layout state being preserved across page navigations.
兼容模式:
¥Compatibility mode:
当 后备路由 正在渲染时,或者当
pages目录页面已被 Next.js 自动静态优化 并且路由未准备好时,usePathname可以返回null。¥
usePathnamecan returnnullwhen a fallback route is being rendered or when apagesdirectory page has been automatically statically optimized by Next.js and the router is not ready.当在
next.config或Middleware中使用带有重写的usePathname时,还必须使用useState和useEffect,以避免水合不匹配错误。¥When using
usePathnamewith rewrites innext.configorMiddleware,useStateanduseEffectmust also be used in order to avoid hydration mismatch errors.如果 Next.js 在你的项目中检测到
app和pages目录,它将自动更新你的类型。¥Next.js will automatically update your types if it detects both an
appandpagesdirectory in your project.
参数
¥Parameters
tsx
const pathname = usePathname()usePathname 不带任何参数。
¥usePathname does not take any parameters.
返回
¥Returns
usePathname 返回当前 URL 路径名的字符串。例如:
¥usePathname returns a string of the current URL's pathname. For example:
| URL | 返回值 |
|---|---|
/ | '/' |
/dashboard | '/dashboard' |
/dashboard?v=2 | '/dashboard' |
/blog/hello-world | '/blog/hello-world' |
示例
¥Examples
响应路由变化做一些事情
¥Do something in response to a route change
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 已引入。 |