目录
一.react异步加载组件,分模块加载,提高打开性能
二.
三.
四.
一.react异步加载组件,分模块加载,提高打开性能
react异步加载的方法很多,这里只说一种,因为这一种直接使用react的特性就可以了,不需要另外配置webpack,就是用一个小技巧去import组件,所以方便,实现简单。
写一个组件A,这个组件内部会加载另外的组件B,用B的内容完全覆盖到A上面,
路由需要打开A的时候,内容加载的B才会调起,达到异步效果,而B就是我们真正想打开的组件,
文章最后给返回组件A的代码。
图片描述
接看上面截图,asyncComponent是一个函数,调用它会返回组件A,A内部加载我们想要的组件B,asyncComponent算是一个工厂函数,可以返回组件A,构造组件A需要传进去一个函数,这个函数直接返回我们想要的组件B。
asyncComponent会用拿到的组件B来渲染组件A,所以虽然打开的是组件A,但组件A本身是空的,把组件B完全融合进去之后,其实A就变成跟B一样了,
这算是一种mixin技术。
代码中其中一个红框圈出来的AsyncStart,就是asyncComponent返回的组件,构造时传给它的函数返回的就是我们想要import的组件start,asyncComponent函数内部把start融入AsyncStart后再返回,这样,我们得到跟start一样的另一个组件。
再看看路由,像普通组件那样引用 AsyncStart就行,最后构建的结果是多个js文件(左边文件列表圈出),用浏览器打开页面后可以看引用的源文件,每次打开一个新页面,才引入一个新的js,确实是异步按需加载的,如下图:
图片描述
下面给出asyncComponent组件的代码:
import React, {Component} from 'react';
const asyncComponent = (importComponent) => {
return class extends Component {
state = {
component: null
}
componentDidMount() {
importComponent() //我们传进来的函数返回我们想要的组件B
.then(cmp => {
this.setState({component: cmp.default}); //把组件B存起来
});
}
render() {
const C = this.state.component; //渲染的时候把组件B拿出来
return C ? <C {...this.props}/> : null; //返回的其实就是组件B,并且把传给A的属性也转移到B上
}
}
};
export default asyncComponent;
import React, {Component} from 'react'
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component{
constructor(props){
super(props)
this.state={
component:null
}
}
componentDidMount() {
importComponent().then((mod)=>{ //我们传进来的函数返回我们想要的组件B
this.setState({
component:mod.default //把组件B存起来
})
})
}
render() {
const C=this.state.component //渲染的时候把组件B拿出来
return C? <C {...this.props}/>:null //返回的其实就是组件B,并且把传给A的属性也转移到B上
}
}
}
网友评论