為什么要使用異步加載組件
因?yàn)轫?xiàng)目中存在一些不必要的狀態(tài)重復(fù)計(jì)算和UI重復(fù)渲染杖小,為了做出優(yōu)化蝙寨,所有就有了異步加載組件
使用方法
AsyncComponent.js(工具方法)
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({
// 同時(shí)兼容ES6和CommonJS的模塊
component: mod.default ? mod.default : mod
});
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return AsyncComponent;
}
開(kāi)始使用
import asyncComponent from 'asyncComponent.js的相對(duì)路徑';
// 使用異步組件加載工具方法加載組件
const AsyncHome = asyncComponent(() => import('../Home'));
const AsyncLogin = asyncComponent(() => import('../Login'));
// 使用異步組件
<BrowserRouter>
<Switch>
<Route path='/' component={AsyncHome} />
<Route path='/login' component={AsyncLogin} />
<Route path='/posts' component={AsyncHome} />
</Switch>
</BrowserRouter>
改進(jìn)版本
在上個(gè)版本的異步組件中,還可以對(duì)其進(jìn)行優(yōu)化鲁猩,這里我們通過(guò)創(chuàng)建一個(gè)高階組件內(nèi)重寫(xiě)組件的 shouldComponentUpdate 方法打厘,如果 Route傳遞的 location 屬性未發(fā)生改變(也就是在同一個(gè)頁(yè)面),就返回 false ,從而阻止組件繼續(xù)更新磅网,然后使用這個(gè)高階組件報(bào)過(guò)沒(méi)一個(gè)要在Route 中使用的組件
connectRoute.js(工具方法)
import React from "react";
export default function connectRoute(WrappedComponent) {
return class ConnectRoute extends React.Component {
shouldComponentUpdate(nextProps) {
return nextProps.location !== this.props.location;
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
開(kāi)始使用
import asyncComponent from "../../utils/AsyncComponent";
import connectRoute from "../../utils/connectRoute";
const AsyncHome = connectRoute(asyncComponent(() => import("../Home")));
const AsyncLogin = connectRoute(asyncComponent(() => import("../Login")));
<BrowserRouter>
<Switch>
<Route exact path="/" component={AsyncHome} />
<Route path="/login" component={AsyncLogin} />
<Route path="/posts" component={AsyncHome} />
</Switch>
</BrowserRouter>