实现异步加载的方法,归根结底大都是根据webpack的require.ensure来实现
第一个是自己使用require.ensure实现,
第二种 使用loader实现
今天我们说的是使用bundle-loader来实现,这样代码更优雅些。
首先需要安装bundle-loader ,具体使用npm还是yarn,就看你的包管理使用的是啥了。
下面需要一个bundle.js
import React, { Component } from 'react';
export default class Bundle extends 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
});
props.load(mod => {
this.setState({
mod: mod.default ? mod.default : mod
});
});
}
render() {
return this.state.mod ? this.props.children(this.state.mod) : null;
}
}然后把bundle.js 引进来,同时也把需要做异步的文件引进来,但是前面需要添加
bundle-loader?lazy&name=[name]!
比如:
import Bundle from './components/bundle.js'; import ListComponent from 'bundle-loader?lazy&name=[name]!./file/List.jsx';
下面就是添加路由这块的配置:
<Route path="/list" component={List} />以及配置output的chunkFilename
chunkFilename: '[name]-[id].[chunkhash:4].bundle.js'
chunkFilename配置好以后,异步加载进来的文件名称就会按照上面的命名方式来展示,如果不配置,就是webpack给生成的数字了。
上面的都配置好了以后,就是怎么使用bundle了,你看到route上配置的component对应的是List,所以我们需要写一个List:
const List = (props) => (
<Bundle load={ListComponent}>
{(List) => <List {...props}/>}
</Bundle>
);上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
使用JS如何实现瀑布流插件
在JS中如何实现将html转为pdf功能
使用JS如何实现粘贴板复制功能
在JS中如何实现offset和匀速动画
在Bootstrap中如何实现表格合并单元格
在JavaScript中如何实现获取select下拉框中第一个值
在AngularJS中如何做到实时获取并显示密码
Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务