如今前端新項目大部分都是單頁引用,爲了減小首頁加載時間過長不少公司會選擇懶加載或服務端渲染,服務端渲染基本上屬於重構了,不但前端要改大量代碼 後端也要作不少配置處理,耗時比較長前端
本文主要聊聊懶加載,react版本更新比較快 懶加載主要有四種,有些已廢棄不推薦使用,本文就講最好用、最簡單的一種配置react
新建lazy文件夾和lazy/index.js文件,內容以下後端
import React from 'react'; const asyncComponent = (importComponent) => { return class extends React.Component { constructor() { super(); this.state = { component: null } } componentDidMount() { importComponent() .then(cmp => { this.setState({ component: cmp.default }); }); } render() { const C = this.state.component; return C ? <C {...this.props} /> : null; } } }; export default asyncComponent;
route/index.js修改以下瀏覽器
import React from 'react'; import {Switch, Route} from "react-router-dom"; import asyncComponent from '../lazy'; import Home2 from '../pages/Home2'; import OnePage from '../pages/OnePage'; import TwoPage from '../pages/TwoPage'; import This from '../pages/This'; import Mount from '../pages/Mount'; import HooksTest1 from '../hooks/test1'; //import HooksUseState from '../hooks/useState'; const HooksUseState = asyncComponent(() => import ('../hooks/useState')); const Routers = ( <Switch> <Route path="/" exact component={Home2} /> <Route path="/onePage" component={OnePage} /> <Route path="/twoPage/:id" component={TwoPage} /> <Route path="/this" component={This} /> <Route path="/mount" component={Mount} /> <Route path="/hooksTest1" component={HooksTest1} /> <Route path="/hooksUseState" component={HooksUseState} /> </Switch> ); export default Routers
//import HooksUseState from '../hooks/useState'; const HooksUseState = asyncComponent(() => import ('../hooks/useState'));
修改的就是這兩行第一行是普通加載方式、改爲第二行就是懶加載了,只須要把import asyncComponent from '../lazy';引入進來就能夠用了,其餘頁面若是須要就這樣改就OK了
下面看看瀏覽器裏有沒有真的實現懶加載吧,首先啓動項目,默認打開路徑 http://localhost:3000/#/,F12打開控制檯,點擊network你應該看到的是這樣的
控制檯顯示加載了9個文件,若是你切換路由到其餘頁面,控制檯的文件不會多加載了,說明咱們一開始就把全部的文件都加載完畢了,只有懶加載的沒有加載,而後咱們切換到 http://localhost:3000/#/hooksUseState
控制檯多加載了一個JS文件,說明懶加載配置成功~