2018-10-12 09:29:45   Visit  10

React 项目通过create-react-app 命令创建,版本为2.0.3.

封装一个高阶组件,用来实现将普通的组件转换成动态组件

import React from \\\\\\\'react\\\\\\\'

const AsyncComponent = loadComponent => (
  class AsyncComponent extends React.Component {
    state = {
      Component: null,
    }

    componentWillMount() {
      if (this.hasLoadedComponent()) {
        return;
      }

      loadComponent()
        .then(module => module.default)
        .then((Component) => {
          this.setState({Component});
        })
        .catch((err) => {
          console.error(`Cannot load component in <AsyncComponent />`);
          throw err;
        });
    }

    hasLoadedComponent() {
      return this.state.Component !== null;
    }

    render() {
      const {Component} = this.state;
      return (Component) ? <Component {...this.props} /> : null;
    }
  }
);

export default AsyncComponent;

修改之前的路由配置

import React from \\\"react\\\";
import {
    Route
} from \\\'react-router-dom\\\'

import asyncComponent from \\\'./asyncComponent\\\'

//import Map from \\\"../pages/Map\\\";

const MapTest = asyncComponent(
    () => import(/* webpackChunkName: \\\"map_test\\\" */\\\'../pages/Map\\\')
)


export default (
    <Route key=\\\"map\\\" path=\\\'/map\\\' component={MapTest} />
);

配置完成后从其他模块切换到map会发现请求了 map_test.trunk.js

参考
https://segmentfault.com/a/1190000011765141

©2017 Leechg.com