React中使用Suspense


疑問

問: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> ); }


文章就分享到這,歡迎關注“前端大神之路

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM