场景
当你的组件很大的时候,可以将组件作为一个异步组件,这样打包后你的组件会是一个独立的文件,用到的时候才载入。
相关API
- import()
- React.lazy
- Suspense
import()举例
使用之前:
import { add } from './math';
console.log(add(16, 26));
使用之后:
import("./math").then(math => {
console.log(math.add(16, 26));
});
React.lazy举例
使用之前:
import OtherComponent from './OtherComponent';
使用之后:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
Suspense举例
import React, { Suspense } from 'react';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}
fallback 属性接受任何在组件加载过程中你想展示的 React 元素。
路由懒加载
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
</Switch>
</Suspense>
</Router>
);
参考资料
https://zh-hans.reactjs.org/docs/code-splitting.html