admin管理员组

文章数量:1278880

Is it possible to use a <Loading /> ponent 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 ponent 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.

Is it possible to use a <Loading /> ponent 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 ponent 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.

Share Improve this question asked Jan 22, 2019 at 16:50 tsdextertsdexter 2,9914 gold badges38 silver badges60 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Yes, it is possible to use another ponent 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 ponentDidMount. 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 es 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 }

  ponentDidMount() {
    // Logging to prove _app.js only mounts once,
    // but initializing router events here will also acplishes
    // 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;

Use the hook below to inspect router's loading status:

import Router from 'next/router'
import { useState, useEffect } from 'react'

const useRouterLoading = () => {
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    const start = () => setLoading(true)
    const end = () => setLoading(false)
    Router.events.on('routeChangeStart', start)
    Router.events.on('routeChangeComplete', end)
    Router.events.on('routeChangeError', end)
    return () => {
      Router.events.off('routeChangeStart', start)
      Router.events.off('routeChangeComplete', end)
      Router.events.off('routeChangeError', end)
    }
  }, [])
  return loading
}

本文标签: javascriptNextJS How can I use a loading component instead of nprogressStack Overflow