1. 路由按需加載:react
不作按需加載,代碼所有打包在bundle.js 文件裏,首屏渲染很慢,項目文件較多,會出現1分鐘加載的可能性。redux
import React, { Component } from 'react'; import Loadable from 'react-loadable'; // 按需加載依賴包 import {HashRouter,Route,Switch} from "react-router-dom" const Loading = () => <div>Loading...</div>; const A = Loadable({ //A頁面 按需加載處理 loader: () => import('../pages/page1'), loading:Loading, }); const B = Loadable({ // B頁面 按需加載處理 loader: () => import('../pages/page2'), loading:Loading, }); class App extends Component { render() { return ( <HashRouter> <Switch> <Route exact path={"/a"} component={A}/> // 加載A組件 <Route exact path={"/b"} component={B}/> <Route component={A}/> </Switch> </HashRouter> ); } } export default App;
如此簡單;數組
2.路由權限配置瀏覽器
場景:後臺管理系統,有用戶管理(增刪改查),訂單管理(發貨,刪除,修改,查看),資金流水(收益查看,提現)等一系列模塊,不一樣身份的人註冊登陸進來,展現不一樣的模塊;react-router
思路: (1) 註冊登陸進來,獲取此人的權限,配置相應的路由。(2)瀏覽器刷新,需從新獲取此人的權限,配置路由。dom
import React, { Component } from 'react'; import Loadable from 'react-loadable'; import Permission from "./permission" import {HashRouter,Route,Switch} from "react-router-dom" const Loading = () => <div>Loading...</div>; const A = Loadable({ loader: () => import('../pages/page1'), loading:Loading, }); const B = Loadable({ loader: () => import('../pages/page2'), loading:Loading, }); class App extends Component { render() { return ( <HashRouter> <Switch> <Route exact path={"/a"} component={A}/> <Route exact path={"/b"} component={B}/> <Route path={"/admin"} component={Permission}/> //須要權限訪問的路由所有放置此組件裏處理,permission組件 <Route component={A}/> </Switch> </HashRouter> ); } } export default App;
permission組件this
import React,{Component} from "react" import {getPermissin} from "../actionCreaters" import {Route,Switch} from "react-router-dom" import {connect} from "react-redux" import A from "../pages/page1" class Permission extends Component{ render(){ if(this.props.permissions.length === 0 ){ //權限存儲在redux中,若是隻在登陸或註冊獲取權限配置,刷新時,將被清空。因此實時的配置路由守衛裏,當權限數組爲空時,請求接口獲取權限 this.props.requestForPermission(); return <div>請等待....</div> } const routers = this.props.permissions.map(item=>{ // 獲取到權限進行路由配置 return <Route exact path={`/admin/${item.code}`} render={()=><div>歡迎{item.code}</div>} key={item.code}/> }); return <Switch> {routers} <Route component={A}/> //匹配不到此路由,跳轉到A組件 </Switch>; } } export default connect((state)=>{ return { permissions:state.author.permissions } },(dispatch)=>{ return { requestForPermission(){ dispatch(getPermissin()); } } })(Permission);
如此簡單;spa
接下來,什麼項目都不怕啦~code