React.lazy
React.lazy
這個函數需要動態調用 import()
。它必須返回一個 Promise,該 Promise 需要 resolve 一個 defalut export
的 React 組件。
然后應在 React.Suspense
組件中渲染 lazy 組件,如此使得我們可以使用在等待加載 lazy 組件時做優雅降級(如 loading 指示器等)。
比如:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}
React.Suspense
React.Suspense
一般用於包裹lazy組件使得組件可以“等待”某些操作結束后,再進行渲染。
通過fallback
可以指定加載指示器(loading indicator),以防其組件樹中的某些子組件尚未具備渲染條件。
可以用Suspense包裹多個懶加載組件,而不必為每一懶加載組件包裹一層Suspense
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const AnotherComponent = React.lazy(() => import('./AnotherComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<section>
<OtherComponent />
<AnotherComponent />
</section>
</Suspense>
</div>
);
}
>React.lazy 目前只支持 default exports ,一個文件中export 了多個模塊,則需要創建一個中間模塊,來重新導出為默認模塊。這能保證 tree shaking 不會出錯,並且不必引入不需要的組件。
//ManyComponent.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;
// MyComponent.js
export { MyComponent as default } from "./ManyComponents.js";
// MyApp.js
import React, { lazy } from 'react';
const MyComponent = lazy(() => import("./MyComponent.js"));