react路由懒加载 --- react-loadable
程序员文章站
2024-03-14 20:46:11
...
// 先下载react-loadable
npm i react-loadable -S
// 建立一个loadable.js,放在src/until/loadable.js
//引入插件,并导出
import Loadable from 'react-loadable';
export default function withLoadable(comp) {
return Loadable({
//懒加载组件页面
loader: comp,
loading: () => null,
delay: "",
})
}
// 在路由页面统一配置, /router/index 页面引入
import { HashRouter as Router, Route, Switch, Redirect } from 'react-router-dom'; ---引入路由
import loadable from '../until/loadable' ---引入懒加载
import Home from '../views/Home'; ---非懒加载页面
// 声明引入的组件通过import引入
const About = loadable(() => import('../views/About.js'))
// 路由数据配置
routerList: [
{ path: '/', component: Home, exact: true },
{ path: '/home', component: Home },
{ path: '/about', component: About },
{ path: '/404', component: Notfound }
]
完整页面
import React, { Component } from 'react';
import { HashRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import loadable from '../until/loadable'
import Home from '../views/Home';
// 路由懒加载
const List = loadable(() => import('../views/List.js'))
const About = loadable(() => import('../views/About.js'))
const Hooks = loadable(() => import('../views/Hooks'))
const Notfound = loadable(() => import('../views/Notfound'))
export default class index extends Component {
constructor(props) {
super(props);
this.state = {
routerList: [
{ path: '/', component: Home, exact: true },
{ path: '/home', component: Home },
{ path: '/list', component: List },
{ path: '/about', component: About },
{ path: '/hooks', component: Hooks },
{ path: '/404', component: Notfound }
]
}
}
render() {
return (
<Router>
<Switch>
{this.state.routerList.map((item, index) => <Route key={index} path={item.path} component={item.component} exact={item.exact}></Route>)}
<Redirect path="*" to="/404"></Redirect>
</Switch>
</Router>
)
}
}
上一篇: 求1-n之间的所有素数
下一篇: lombok依赖