关于react.js:react中使用webpack的import异步加载组件的实现

1、asyncComponent函数(惊天函数):函数很好了解,loadComponent参数示意须要代码切割的门路,函数返回值是一个react组件,组件外部帮你做好了then()办法的操作。

import React from 'react'
export 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;
        }
    }
);

2、在react中应用

import { asyncComponent } from './AsyncComponent'

const Foo = asyncComponent(() => import(/* webpackChunkName: "foo" */ "./foo"))

<Route path="/xx" component={Foo} />

3、好了,这样你就胜利了,然而,请留神上面几个问题:

webpack2的配置文件中,须要配置chunkName。

chunkFilename: '[name].js'

如果你的异步加载组件有导入款式,请把款式移植到全局js文件导入。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理