Next 的 App Router 下,如何加入页面跳转的进度条?
❓加一个进度条
问题起因是我想给自己博客页面切换时加一个进度条,博客前端技术栈是 React,使用 Next 做了 SSR。在这方面有非常成熟的库 NProgress,只需要调用NProgress.start()
和NProgress.done()
即可开启和结束进度条。我们只需要在页面开始、结束切换时调用即可。
🌐Page Router 模式的做法
在 Page Router 模式下,可以使用router.events
的 API 去监听路由切换:
ts- import { useEffect } from 'react'
- import { useRouter } from 'next/router'
- import NProgress from 'nprogress'
- import 'nprogress/nprogress.css'
- export function useProgressBar() {
- const router = useRouter()
- NProgress.configure({ showSpinner: false, speed: 400 })
- useEffect(() => {
- const startHandler = () => {
- NProgress.start()
- };
- const completeHandler = () => {
- NProgress.done()
- };
- router.events.on('routeChangeStart', startHandler)
- router.events.on('routeChangeComplete', completeHandler)
- }, [])
- }
是不是很方便呢,在 App Router 模式下就难搞了。
🛠App Router 模式的做法
App Router 模式基于 React 的服务端组件对渲染的模式进行了更细致的划分,这看起来就很 Coooooooool,除了某些 API 不太方便之外。在 App Router 模式,没有监听路由跳转发起的 API,只能通过监听路径(usePathname
、useParams
)、query 参数(useSearchParams
)等方式知道路由已经发生变化了。
参考一下在 Next 看了一下 issue [Next 13] router.events removed?、[next/navigation] Next 13: useRouter events? 下面的讨论,监听路由开始切换,可以通过监听Link
标签的click
事件实现,具体操作是使用MutationObserver
监听document
,在子树变更时搜索所有Link
标签加上监听器。然后通过代理history.pushState
、history.replaceState
来在路由变更后关闭进度条。借鉴 issue 中讨论的做法,我这里自定义了 Hook 函数来实现这一点。
ts- import { useEffect } from 'react'
- import NProgress from 'nprogress'
- import 'nprogress/nprogress.css'
- type PushStateInput = [any, string, string | URL | null | undefined]
- const handleAnchorClick = (event: MouseEvent) => {
- // 新窗口打开不需要进度条
- if (event.ctrlKey || event.metaKey) {
- return
- }
- const targetUrl = (event.currentTarget as HTMLAnchorElement).href
- const currentUrl = window.location.href
- if (targetUrl !== currentUrl) {
- NProgress.start()
- }
- }
- export const useProgressBar = () => {
- useEffect(() => {
- NProgress.configure({ showSpinner: false, speed: 400 })
-
- const handleMutation: MutationCallback = () => {
- const anchorElements: NodeListOf<HTMLAnchorElement> = document.querySelectorAll('a[href]')
- anchorElements.forEach((anchor) => anchor.addEventListener('click', handleAnchorClick))
- }
-
- const mutationObserver = new MutationObserver(handleMutation)
- mutationObserver.observe(document, { childList: true, subtree: true })
-
- window.history.pushState = new Proxy(window.history.pushState, {
- apply: (target, thisArg, argArray: PushStateInput) => {
- NProgress.done()
- return target.apply(thisArg, argArray)
- },
- })
- window.history.replaceState = new Proxy(window.history.replaceState, {
- apply: (target, thisArg, argArray: PushStateInput) => {
- NProgress.done()
- return target.apply(thisArg, argArray)
- },
- })
- }, [])
- }
如果是使用router.push
切换路由,类似地,我们也触发一次进度条就好了:
ts- import NProgress from 'nprogress'
- import { useRouter } from 'next/navigation'
- import { NavigateOptions } from 'next/dist/shared/lib/app-router-context.shared-runtime'
- type NextNavPushArgsType = [string, NavigateOptions | undefined]
- export const useProgressRouter = () => {
- const router = useRouter()
- router.push = new Proxy(router.push, {
- apply: (target, thisArg, argArray: NextNavPushArgsType) => {
- NProgress.start()
- return target.apply(thisArg, argArray)
- },
- })
- router.replace = new Proxy(router.replace, {
- apply: (target, thisArg, argArray: NextNavPushArgsType) => {
- NProgress.start()
- return target.apply(thisArg, argArray)
- },
- })
- return router
- }
📖结语
针对 App Router 模式下没有给出监听路由切换的特定 API 的情况,为了实现进度条的开始和结束。通过MutationObserver
,我们通过监听所有Link
标签的点击事件来开启进度条。包装history.pushState
等 API,实现路由切换结束关闭进度条。另外,对使用router.push
等情况,我们通过增强router
来使其拥有开启进度条的功能。