码迷,mamicode.com
首页 > Windows程序 > 详细

React中异步模块api React.lazy和React.Suspense

时间:2019-09-25 09:20:57      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:llb   resolve   block   lazy   api   懒加载   降级   other   ISE   

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

React中异步模块api React.lazy和React.Suspense

标签:llb   resolve   block   lazy   api   懒加载   降级   other   ISE   

原文地址:https://www.cnblogs.com/zzy1996/p/11582152.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!