首页 > 解决方案 > 在反应路由器配置中编写异步组件以进行延迟加载

问题描述

我是新来的反应。尝试延迟加载组件。我正在使用服务器端渲染以及反应路由器配置。我需要延迟加载组件。

asyncComponent.js

import React, { PureComponent } from 'react';

export default class  extends PureComponent {
 constructor(props) {
super(props);

this.state = {
  Component: null
}
}

componentWillMount() {
if(!this.state.Component) {
  this.props.moduleProvider().then( ({Component}) => this.setState({ Component }));
}
}

render() {
const { Component } = this.state;

//The magic happens here!
return (
  <div>
    {Component ? <Component /> : ''}
  </div>
);
 }
 };

路由.js

import React from 'react';
import App from './app';
import asyncComponent from './asyncComponent';

const Home = asyncComponent.moduleProvider(import('./components/Home'));

const routes = [{
    component: App,
    routes: [
        {
          path : '/',
          exact: true,
          component: Home
        }
    ]
}];

export default routes;

我参考了 [ https://github.com/rubenspgcavalcante/react-webpack-lazy-loading.git][1]中的示例

这是抛出异常。这是正确的方法吗?

标签: javascriptreactjsreact-router-v4

解决方案


推荐阅读