欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

react中Suspense的使用详解

程序员文章站 2023-11-05 18:27:28
关于suspense的使用,先来看下示例代码 const othercomponent = react.lazy(() => import('./other...

关于suspense的使用,先来看下示例代码

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。