路由懒加载是什么意思?
在开发中 , 我们打开开发者工具, 会发现我们刚刚打开就会去加载所有页面.
路由懒加载就是只加载你当前点击的那个模块
按需去加载路由对应的资源, 可以提高加载速度 (一个页面加载过后再次访问不会重复加载)
实现原理:将路由相关的组件,不再直接导入了,而是改写成异步组件的写法,只有当函数被调用的时候,才去加载对应的组件内容
方法一: 重写
首先, 新建一个asynccComponent.js , 作为公共js
import {Component as ReactComponet} from 'react'
import React from "react";
export default function asyncComponent(getComponent) {
return class AsyncComponent extends ReactComponet {
state = {Component: null}
componentDidMount() {
if (!this.state.Component) {
getComponent().then(Component => {
this.setState({Component})
})
}
}
render() {
const {Component} = this.state
if (Component) {
return <Component {...this.props} />
}
return null
}
}
}
然后写一个async-page.js 引入需要按需加载的页面
import asyncCompo