react-router v4 代码分割/按需加载

2017-10-30  本文已影响0人  jiansheng

首先新建文件Bundle.js。

// Bundle.js

import React from 'react';

export default class Bundle extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mod: null
        };
    }

    componentWillMount() {
        this.load(this.props)
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.load !== this.props.load) {
            this.load(nextProps)
        }
    }

    load(props) {
        this.setState({
            mod: null
        });
        //注意这里,使用Promise对象; mod.default导出默认
        props.load().then((mod) => {
            this.setState({
                mod: mod.default ? mod.default : mod
            });
        });
    }

    render() {
        return this.state.mod ? this.props.children(this.state.mod) : null;
    }
}

然后如下使用即可。

11.png

效果:
刚开始在 / 路由,加载到的文件有

22.png

然后到 /todo-app 路由,加载的文件有

33.png

红色框中的 0.chunk.js 就是到 /todo-app 路由,按需加载到的文件。

上一篇 下一篇

猜你喜欢

热点阅读