前言

next.js框架是支流的SSR框架,弱小的开箱即用加上社区十分沉闷让它可能在泛滥框架中怀才不遇。最近为了实现next.js页面之间来回跳转加上loading成果晋升用户体验写下这篇文章,心愿可能帮忙到大家。

操作

首先,咱们来剖析一下实现原理,首先路由之间跳转启动与完结要有监听事件,用到的就是next.js的router监听事件

有了监听事件咱们就可能很好的管制页面之间的跳转。

接着咱们须要一个loading bar置顶到页面最下面,这里咱们会用到@tanem/react-nprogress这个插件。

yarn add @tanem/react-nprogress

接着,咱们关上这个地址,复制外面的代码到咱们的我的项目中。

1、新建globalLoading.js

import React from 'react';import { useNProgress } from '@tanem/react-nprogress';const GlobalLoading = ({ isRouteChanging, }) => {  const { animationDuration, isFinished, progress } = useNProgress({    isAnimating: isRouteChanging,  })  return (    <>      <style jsx>{`        .container {          opacity: ${isFinished ? 0 : 1};          pointerevents: none;          transition: opacity ${animationDuration}ms linear;        }        .bar {          background: #29d;          height: 2px;          left: 0;          margin-left: ${(-1 + progress) * 100}%;          position: fixed;          top: 0;          transition: margin-left ${animationDuration}ms linear;          width: 100%;          z-index: 1031;        }        .spinner {          box-shadow: 0 0 10px #29d, 0 0 5px #29d;          display: block;          height: 100%;          opacity: 1;          position: absolute;          right: 0;          transform: rotate(3deg) translate(0px, -4px);          width: 100px;        }      `}</style>      <div className="container">        <div className="bar">          <div className="spinner" />        </div>      </div>    </>  )};export default GlobalLoading;

2、批改_app.js

const MyApp = ({Component, pageProps}) => {  const router = useRouter()  const [state, setState] = useState({    isRouteChanging: false,    loadingKey: 0,  })  useEffect(() => {    const handleRouteChangeStart = () => {      setState((prevState) => ({        ...prevState,        isRouteChanging: true,        loadingKey: prevState.loadingKey ^ 1,      }))    }    const handleRouteChangeEnd = () => {      setState((prevState) => ({        ...prevState,        isRouteChanging: false,      }))    }    router.events.on('routeChangeStart', handleRouteChangeStart)    router.events.on('routeChangeComplete', handleRouteChangeEnd)    router.events.on('routeChangeError', handleRouteChangeEnd)    return () => {      router.events.off('routeChangeStart', handleRouteChangeStart)      router.events.off('routeChangeComplete', handleRouteChangeEnd)      router.events.off('routeChangeError', handleRouteChangeEnd)    }  }, [router.events])  return <>    <GlobalLoading isRouteChanging={state.isRouteChanging} key={state.loadingKey} />    <Component {...pageProps} />  </>}export default wrapper.withRedux(MyApp)

这样就实现了所有代码的编写,接着,咱们运行下我的项目,看看页面之间来回切换是否领有了loading bar的成果了。

Nice!

演示地址

总结

理解实现原理再加上社区牛人的奉献,记住常去next.js官网看看最新的动向以及新版本新加了哪些性能,比方最近next.js 12增加了middleware性能等等。

援用

next.js loading bar视频教程
next.js middleware