最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

NextJS:如何使用装载组件,而不是nprogress?

运维笔记admin18浏览0评论

NextJS:如何使用装载组件,而不是nprogress?

NextJS:如何使用装载组件,而不是nprogress?

是否有可能在NextJS而不是nprogress使用<Loading />成分?我想你需要访问像pageProps一些高层次的道具从路由器事件,以便您可以切换负载状态,然后有条件地输出一个加载组件,但我不明白的方式来做到这一点?

例如,

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

而在渲染

const { Component, pageProps } = this.props;

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

但当然,routeChangeStart不pageProps通过。

回答如下:

是的,这是可以使用其他组件来处理负载,而不是nProgress。我也有类似的问题,发现下面的工作为我的解决方案。

这是有道理的做这一切在./pages/_app.js,因为according to the documentation可以用持续的页面之间的布局和状态有所帮助。您可以发起生命周期方法componentDidMount路由器的事件。需要注意的是_app.js仅仅将一次是很重要的,但启动路由器事件仍然会在这里工作。这将使你能够设置状态。

下面是这一切是如何走到一起的例子:

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;
发布评论

评论列表(0)

  1. 暂无评论