疑問
問:React Suspense有什么用呢?
答:在動態導入的幫助下,React Suspense讓我們輕松定義延遲加載的組件。
代碼demo
const OtherComponent = React.lazy(() => import('./OtherComponent')); function MyComponent() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense> </div> ); }
OtherComponent是通過懶加載加載進來的,所以渲染頁面的時候可能會有延遲,但使用了Suspense之后,可優化交互。在
<OtherComponent />外面使用Suspense標簽,並在fallback中聲明OtherComponent加載完成前做的事,即可優化整個頁面的交互
fallback屬性接受任何在組件加載過程中你想展示的 React 元素。你可以將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> ); }


