NextJS: How can I use a loading component instead of nprogress?

♀尐吖头ヾ 提交于 2020-06-25 05:30:19

问题


Is it possible to use a <Loading /> component in NextJS instead of nprogress? I'm thinking you would need to access some high level props like pageProps from the router events so you can toggle the loading state and then conditionally output a loading component but I don't see a way to do this...

For example,

Router.events.on("routeChangeStart", (url, pageProps) => {
  pageProps.loading = true;
});

and in the render

const { Component, pageProps } = this.props;

return pageProps.loading ? <Loading /> : <Page />;

But of course, routeChangeStart doesn't pass in pageProps.


回答1:


Yes, it is possible to use another component to handle loading instead of nProgress. I had a similar question, and found the solution below working out for me.

It makes sense to do all this in ./pages/_app.js, because according to the documentation that can help with persisting layout and state between pages. You can initiate the Router events on the lifecycle method componentDidMount. It's important to note that _app.js only mounts once, but initiating Router events will still work here. This will allow you to be able to set state.

Below is an example of how this all comes together:

import React, { Fragment } from 'react';
import App from 'next/app';
import Head from 'next/head';
import Router from 'next/router';

class MyApp extends App {
  state = { isLoading: false }

  componentDidMount() {
    // Logging to prove _app.js only mounts once,
    // but initializing router events here will also accomplishes
    // goal of setting state on route change
    console.log('MOUNT');

    Router.events.on('routeChangeStart', () => {
      this.setState({ isLoading: true });
    });

    Router.events.on('routeChangeComplete', () => {
      this.setState({ isLoading: false });
    });

    Router.events.on('routeChangeError', () => {
      this.setState({ isLoading: false });
    });
  }

  render() {
    const { Component, pageProps } = this.props;
    const { isLoading } = this.state;

    return (
      <Fragment>
        <Head>
          <title>My App</title>
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <meta charSet="utf-8" />
        </Head>
        {/* You could also pass isLoading state to Component and handle logic there */}
        <Component {...pageProps} />
        {isLoading && 'STRING OR LOADING COMPONENT HERE...'}
      </Fragment>
    );
  }
}

MyApp.getInitialProps = async ({ Component, ctx }) => {
  let pageProps = {};

  if (Component.getInitialProps) {
    pageProps = await Component.getInitialProps(ctx);
  }

  return { pageProps };
};

export default MyApp;


来源:https://stackoverflow.com/questions/54312927/nextjs-how-can-i-use-a-loading-component-instead-of-nprogress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!