1 )概述
2 )示例程序
lazy.js
// lazy.js
import React from 'react'
export default () => <p>Lazy Comp</p>
主程序
import React, { Suspense, lazy } from 'react'
const LazyComp = lazy(() => import('./lazy.js'))
let data = ''
let promise = ''
function requestData() {
if (data) return data
if (promise) throw promise
promise = new Promise(resolve => {
setTimeout(() => {
data = 'Data resolved'
resolve()
}, 2000)
})
throw promise
}
function SuspenseComp() {
const data = requestData()
return <p>{data}</p>
}
export default () => (
<Suspense fallback="loading data">
<SuspenseComp />
<LazyComp />
</Suspense>
)
Suspense
,然后给它一个 fallback 的 propSuspense
组件,下面渲染一个或者多个这种异步的组件
Suspense
的功能后期发布Suspense
支持 lazy组件,可以非常方便的实现异步组件加载
const LazyComp = lazy(() => import('./lazy.js'))
Suspense
里面Suspense
组件内部有多个组件,要等到所有的组件都resolved之后Suspense
的一个特点3 ) 源码探究
定位到 React.js, 找到 Suspense
import {
REACT_SUSPENSE_TYPE,
} from 'shared/ReactSymbols';
import { lazy } from './ReactLazy';
const React = {
// ... 此处省略其他
lazy,
// ... 此处省略其他
Suspense: REACT_SUSPENSE_TYPE
}
Suspense
它是一个常量,就是一个 REACT_SUSPENSE_TYPE
,本质上只是一个Symbolimport { lazy } from './ReactLazy';
基于这个,定位到 ReactLazy.js 查看 lazy
源码
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {LazyComponent, Thenable} from 'shared/ReactLazyComponent';
import {REACT_LAZY_TYPE} from 'shared/ReactSymbols';
export function lazy<T, R>(ctor: () => Thenable<T, R>): LazyComponent<T> {
return {
$$typeof: REACT_LAZY_TYPE,
_ctor: ctor,
// React uses these fields to store the result.
_status: -1,
_result: null,
};
}
它是一个方法 export function lazy
,并接收一个方法
lazy<T, R>(ctor: () => Thenable<T, R>): LazyComponent<T>
Thenable
类型的对象Thenable
是 Promise 这样的一个对象,它具有 .then
方法最终,返回的是一个 lazy component
$$typeof
,值为 REACT_LAZY_TYPE
_ctor
就是我们传递进来的回调函数
_ctor
回调,并返回一个 Thenable 的对象(Promise对象)_status
用来记录当前这个 Thenable
的对象,所处的状态
_result
Promise结果
_result
_result
里面的组件渲染就可以了