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

2次阅读

共计 879 个字符,预计需要花费 3 分钟才能阅读完成。

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 文件导入。

正文完
 0