Fork me on GitHub

异步打包详情页面

来源:简书项目
组件:React-loadable
作用:异步加载详情页面
具体:页面首先打包首页,打开详情页的时候,再打包详情页

安装

1
yarn add React-loadable

使用

1、在当前页面 index 所在文件夹下,创建 loadable.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import Loadable from 'React-loadable';
import Loading from './my-loading-component';

const LoadableComponent = Loadable({
loader: () => import('./my-component'),
//需要异步加载的页面,本例是./index.js,index.js可省略
loading: Loading,
//页面加载时展示的loading,可以是一个自己写的组件,或者
//loading(){
// return <div>正在加载</div>
//}

});

export default class App extends React.Component {
render() {
return <LoadableComponent/>;
}
}

2、修改详情页面路由配置

1
2
3
import Detail from './pages/detail/';
//变为
import Detail from './pages/detail/loadable';

3、这样详细页面无法直接访问项目到路由

1
<Route component={component} />

只有写在该标签中的页面才能直接在 this.props.match 访问到路由
修改在 detail 页面代码
引入 withRouter

1
import { withRouter } from 'React-router-dom'

同时包裹 detail 组件

1
export default connect(mapStateToProps,mapDispatchToProps)(withRouter(Detail))
-------------本文结束感谢阅读-------------