關于Suspense的使用,先來看下示例代碼
const OtherComponent = React.lazy(() => import('./OtherComponent'));function MyComponent() { return (  <div>   <Suspense fallback={<div>Loading...</div>}>    <OtherComponent />   </Suspense>  </div> );}OtherComponent是通過懶加載加載進來的,所以渲染頁面的時候可能會有延遲,但使用了Suspense之后,可優(yōu)化交互。
在<OtherComponent />外面使用Suspense標簽,并在fallback中聲明OtherComponent加載完成前做的事,即可優(yōu)化整個頁面的交互
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> );}以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答