主题
useRouter
useRouter 钩子允许你以编程方式更改 客户端组件 内的路由。
¥The useRouter hook allows you to programmatically change routes inside Client Components.
建议:除非你有使用
useRouter的特定要求,否则请使用<Link>组件 进行导航。¥Recommendation: Use the
<Link>component for navigation unless you have a specific requirement for usinguseRouter.
tsx
'use client'
import { useRouter } from 'next/navigation'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
)
}useRouter()
router.push(href: string, { scroll: boolean }):对所提供的路由执行客户端导航。将新条目添加到 浏览器的历史记录 堆栈中。¥
router.push(href: string, { scroll: boolean }): Perform a client-side navigation to the provided route. Adds a new entry into the browser’s history stack.router.replace(href: string, { scroll: boolean }):对所提供的路由执行客户端导航,而无需在 浏览器的历史堆栈 中添加新条目。¥
router.replace(href: string, { scroll: boolean }): Perform a client-side navigation to the provided route without adding a new entry into the browser’s history stack.router.refresh():刷新当前路由。向服务器发出新请求,重新获取数据请求,并重新渲染服务器组件。客户端将合并更新的 React Server 组件有效负载,而不会丢失未受影响的客户端 React(例如useState)或浏览器状态(例如滚动位置)。¥
router.refresh(): Refresh the current route. Making a new request to the server, re-fetching data requests, and re-rendering Server Components. The client will merge the updated React Server Component payload without losing unaffected client-side React (e.g.useState) or browser state (e.g. scroll position).router.prefetch(href: string, options?: { onInvalidate?: () => void }):预请求 提供了更快的客户端转换的路由。可选的onInvalidate回调函数在 预取数据过期 调用时调用。¥
router.prefetch(href: string, options?: { onInvalidate?: () => void }): Prefetch the provided route for faster client-side transitions. The optionalonInvalidatecallback is called when the prefetched data becomes stale.router.back():导航回浏览器历史记录堆栈中的上一条路由。¥
router.back(): Navigate back to the previous route in the browser’s history stack.router.forward():向前导航到浏览器历史记录堆栈中的下一页。¥
router.forward(): Navigate forwards to the next page in the browser’s history stack.
需要了解:
¥Good to know:
你不得将不受信任或未经清理的 URL 发送到
router.push或router.replace,因为这可能会使你的网站面临跨站点脚本 (XSS) 漏洞。例如,发送到router.push或router.replace的javascript:URL 将在你的页面上下文中执行。¥You must not send untrusted or unsanitized URLs to
router.pushorrouter.replace, as this can open your site to cross-site scripting (XSS) vulnerabilities. For example,javascript:URLs sent torouter.pushorrouter.replacewill be executed in the context of your page.当路由在视口中可见时,
<Link>组件会自动预取路由。¥The
<Link>component automatically prefetch routes as they become visible in the viewport.如果提取请求被缓存,
refresh()可能会重新产生相同的结果。其他动态 API(如cookies和headers)也可能更改响应。¥
refresh()could re-produce the same result if fetch requests are cached. Other Dynamic APIs likecookiesandheaderscould also change the response.每个预取请求最多调用一次
onInvalidate回调。它指示何时可能需要触发新的预取以获取更新的路由数据。¥The
onInvalidatecallback is called at most once per prefetch request. It signals when you may want to trigger a new prefetch for updated route data.
从 next/router 迁移
¥Migrating from next/router
使用 App Router 时,应从
next/navigation而不是next/router导入useRouter钩子¥The
useRouterhook should be imported fromnext/navigationand notnext/routerwhen using the App Routerpathname字符串已被删除并替换为usePathname()¥The
pathnamestring has been removed and is replaced byusePathname()query对象已被删除并被useSearchParams()取代¥The
queryobject has been removed and is replaced byuseSearchParams()router.events已被替换。见下文。¥
router.eventshas been replaced. See below.
¥View the full migration guide.
示例
¥Examples
路由事件
¥Router events
你可以通过编写其他客户端组件钩子(例如 usePathname 和 useSearchParams)来监听页面更改。
¥You can listen for page changes by composing other Client Component hooks like usePathname and useSearchParams.
可以将其导入到布局中。
¥Which can be imported into a layout.
需要了解:
<NavigationEvents>包含在Suspense边界 中,因为useSearchParams()导致客户端在 静态渲染 期间渲染到最近的Suspense边界。了解更多。¥Good to know:
<NavigationEvents>is wrapped in aSuspenseboundary becauseuseSearchParams()causes client-side rendering up to the closestSuspenseboundary during static rendering. Learn more.
禁用滚动到顶部
¥Disabling scroll to top
默认情况下,当导航到新路由时,Next.js 将滚动到页面顶部。你可以通过将 scroll: false 传递到 router.push() 或 router.replace() 来禁用此行为。
¥By default, Next.js will scroll to the top of the page when navigating to a new route. You can disable this behavior by passing scroll: false to router.push() or router.replace().
tsx
'use client'
import { useRouter } from 'next/navigation'
export default function Page() {
const router = useRouter()
return (
<button
type="button"
onClick={() => router.push('/dashboard', { scroll: false })}
>
Dashboard
</button>
)
}版本历史
¥Version History
| 版本 | 更改 |
|---|---|
v15.4.0 | 引入了针对 router.prefetch 的可选 onInvalidate 回调 |
v13.0.0 | next/navigation 中的 useRouter 已引入。 |