项目中的代码分割
import 静态引入写法
1 2 3 4 5 6 7 8 9 10 11
| import Home from "./components/Home"; import Login from "./components/Login"; ... return( <Router> <Switch> <Route exact path="/" component={Home} /> <Route path="/login" component={Login} /> <Route path="/posts" component={Home} /> ... )
|
以上写法不管匹配到了哪一个 route,都是一次性地引入所有的组件。可以使用代码分割进行优化,实现只引入匹配到的 route 和对应组件。
创建一个异步组件 asyncComponent 替换 import 动态导入的 Login 和 Home 组件,实现按需异步加载
utils/AsyncComponent/asyncComponent.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| 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 => { this.setState({ component: mod.default ? mod.default : mod }); }); } render() { const C = this.state.component; return C ? <C {...this.props} /> : null; } } return AsyncComponent; }
|
使用 asyncComponent 组件
src/components/App/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import asyncComponent from "../../utils/AsyncComponent";
const AsyncHome = connectRoute(asyncComponent(() => import("../Home"))); const AsyncLogin = connectRoute(asyncComponent(() => import("../Login")));
... return( <div> <Router> <Switch> {} <Route exact path="/" component={AsyncHome} /> <Route path="/login" component={AsyncLogin} /> <Route path="/posts" component={AsyncHome} /> ... ) ...
|
不要把所有的数据都往 State 中塞
如后端数据,且数据为不需要在页面变动
1 2 3 4 5 6 7 8 9 10 11 12
| "data": { "result": { "id": 2, "totalUserCount": 634801, "totalSilentUserCount": 631192, "totalAccountCount": 29012, "creationTime": "2019-12-12T14:46:45.423" }, "isSuccess": true, "errorCode": 0, "message": "" },
|
那么我们只需要把 result 放入 state 即可
1 2 3 4 5 6 7 8 9 10
| this.setState({ Data:result }) const {Data} = this.state .... <span style={{ color: '#333333', fontSize: '14px' }}> <a href="#"> {Data.totalUserCount} </a> 个,
|