dev*_*rav 1 reactjs next.js next.js13
在 Next JS < 13 中,我们router.events可以_app.js添加类似的效果
import { useRouter } from 'next/router'
import NProgress from 'nprogress'
const Main = ({ Component, pageProps }) => {
const router = useRouter()
useEffect(function nprogressOnRouteChange() {
router.events.on('routeChangeStart', NProgress.start)
router.events.on('routeChangeError', NProgress.done)
router.events.on('routeChangeComplete', NProgress.done)
return () => {
router.events.off('routeChangeStart', NProgress.start)
router.events.off('routeChangeError', NProgress.done)
router.events.off('routeChangeComplete', NProgress.done)
NProgress.remove()
}
}, [])
...
}
Run Code Online (Sandbox Code Playgroud)
但现在useRouter已移至next/navigation,并且钩子返回的对象中不再具有任何事件属性,我是否遗漏了什么?
尝试在新文件中导入Router,但事件也不起作用next/routerlayout.tsx
import Router from 'next/router'
export default function Transition({ children }) {
useEffect(() => {
Router.events.on('routeChangeStart', () => {
console.log('start')
})
}, [])
...
}
Run Code Online (Sandbox Code Playgroud)
//this worked for me, hope it helps!
//so you turn it on when you leave the page, and off when you land on another page
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
export default async function Home() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
NProgress.done();
return () => {
NProgress.start();
};
}, [pathname, searchParams]);
return (
<>
...
</>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1219 次 |
| 最近记录: |