react-router4按需加载显示loading

react-router4配置了按需加载,现在网络不好情况下分割的js还没请求回来页面是空白的,怎么配置分割的js还没有请求回来之前页面显示一个loading动画,等到对应的分割的js请求回来了之后隐藏掉loading显示页面?

阅读 5.2k
3 个回答

不知道你怎么实现的。
就我的认识中,按需加载时这样实现的。
引入一个控件(控件留一个开关) -> 当调用的时候,打开这个开关

这是一种实现

import React, { Component } from "react";

export default function asyncComponent(importComponent) {
  class AsyncComponent extends Component {
    constructor(props) {
      super(props);

      this.state = {
        component: null
      };
    }

    async componentDidMount() {
      const { default: component } = await importComponent();

      this.setState({
        component: component
      });
    }

    render() {
      const C = this.state.component;
      // 可以在这里加上loading
      //return C ? <C {...this.props} /> : <Loading>;
      return C ? <C {...this.props} /> : null;
    }
  }

  return AsyncComponent;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题