如何在Next JS 13中使用NProgress这样的进度条显示路线更改转换?

tyky79it  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(107)

在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()
        }
    }, [])

    ...
}

字符串
但是现在useRouter已经被移动到next/navigation,钩子返回的对象不再有任何事件属性,我错过了什么吗
我尝试在新的layout.tsx文件中从next/router导入Router,但事件也不起作用

import Router from 'next/router'
export default function Transition({ children }) {
    useEffect(() => {
        Router.events.on('routeChangeStart', () => {
            console.log('start')
        })
    }, [])

    ...
}

3yhwsihp

3yhwsihp1#

//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 (
    <>
     ...
    </>
  )
}

字符串

相关问题