本文介紹與 Suspense
在三種情景下使用方法,并結(jié)合源碼進行相應(yīng)解析。歡迎關(guān)注個人博客。
Code Spliting
在 16.6 版本之前,code-spliting
通常是由第三方庫來完成的,比如 react-loadble(核心思路為: 高階組件 + webpack dynamic import), 在 16.6 版本中提供了 Suspense
和 lazy
這兩個鉤子, 因此在之后的版本中便可以使用其來實現(xiàn) Code Spliting
。
目前階段, 服務(wù)端渲染中的
code-spliting
還是得使用react-loadable
, 可查閱 React.lazy, 暫時先不探討原因。
Code Spliting
在 React
中的使用方法是在 Suspense
組件中使用 <LazyComponent>
組件:
import { Suspense, lazy } from 'react'
const DemoA = lazy(() => import('./demo/a'))
const DemoB = lazy(() => import('./demo/b'))
<Suspense>
<NavLink to="/demoA">DemoA</NavLink>
<NavLink to="/demoB">DemoB</NavLink>
<Router>
<DemoA path="/demoA" />
<DemoB path="/demoB" />
</Router>
</Suspense>
源碼中 lazy
將傳入的參數(shù)封裝成一個 LazyComponent
function lazy(ctor) {
return {
$$typeof: REACT_LAZY_TYPE, // 相關(guān)類型
_ctor: ctor,
_status: -1, // dynamic import 的狀態(tài)
_result: null, // 存放加載文件的資源
};
}
觀察 readLazyComponentType 后可以發(fā)現(xiàn) dynamic import
本身類似 Promise
的執(zhí)行機制, 也具有 Pending
、Resolved
、Rejected
三種狀態(tài), 這就比較好理解為什么 LazyComponent
組件需要放在 Suspense
中執(zhí)行了(Suspense
中提供了相關(guān)的捕獲機制, 下文會進行模擬實現(xiàn)`), 相關(guān)源碼如下:
function readLazyComponentType(lazyComponent) {
const status = lazyComponent._status;
const result = lazyComponent._result;
switch (status) {
case Resolved: { // Resolve 時,呈現(xiàn)相應(yīng)資源
const Component = result;
return Component;
}
case Rejected: { // Rejected 時,throw 相應(yīng) error
const error = result;
throw error;
}
case Pending: { // Pending 時, throw 相應(yīng) thenable
const thenable = result;
throw thenable;
}
default: { // 第一次執(zhí)行走這里
lazyComponent._status = Pending;
const ctor = lazyComponent._ctor;
const thenable = ctor(); // 可以看到和 Promise 類似的機制
thenable.then(
moduleObject => {
if (lazyComponent._status === Pending) {
const defaultExport = moduleObject.default;
lazyComponent._status = Resolved;
lazyComponent._result = defaultExport;
}
},
error => {
if (lazyComponent._status === Pending) {
lazyComponent._status = Rejected;
lazyComponent._result = error;
}
},
);
// Handle synchronous thenables.
switch (lazyComponent._status) {
case Resolved:
return lazyComponent._result;
case Rejected:
throw lazyComponent._result;
}
lazyComponent._result = thenable;
throw thenable;
}
}
}
Async Data Fetching
為了解決獲取的數(shù)據(jù)在不同時刻進行展現(xiàn)的問題(在 suspenseDemo 中有相應(yīng)演示), Suspense
給出了解決方案。
下面放兩段代碼,可以從中直觀地感受在 Suspense
中使用 Async Data Fetching
帶來的便利。
- 一般進行數(shù)據(jù)獲取的代碼如下:
export default class Demo extends Component {
state = {
data: null,
};
componentDidMount() {
fetchAPI(`/api/demo/${this.props.id}`).then((data) => {
this.setState({ data });
});
}
render() {
const { data } = this.state;
if (data == null) {
return <Spinner />;
}
const { name } = data;
return (
<div>{name}</div>
);
}
}
- 在
Suspense
中進行數(shù)據(jù)獲取的代碼如下:
const resource = unstable_createResource((id) => {
return fetchAPI(`/api/demo`)
})
function Demo {
render() {
const data = resource.read(this.props.id)
const { name } = data;
return (
<div>{name}</div>
);
}
}
可以看到在 Suspense
中進行數(shù)據(jù)獲取的代碼量相比正常的進行數(shù)據(jù)獲取的代碼少了將近一半!少了哪些地方呢?
- 減少了
loading
狀態(tài)的維護(在最外層的 Suspense 中統(tǒng)一維護子組件的 loading) - 減少了不必要的生命周期的書寫
總結(jié): 如何在 Suspense 中使用 Data Fetching
當(dāng)前 Suspense
的使用分為三個部分:
第一步: 用 Suspens
組件包裹子組件
import { Suspense } from 'react'
<Suspense fallback={<Loading />}>
<ChildComponent>
</Suspense>
第二步: 在子組件中使用 unstable_createResource
:
import { unstable_createResource } from 'react-cache'
const resource = unstable_createResource((id) => {
return fetch(`/demo/${id}`)
})
第三步: 在 Component
中使用第一步創(chuàng)建的 resource
:
const data = resource.read('demo')
相關(guān)思路解讀
來看下源碼中 unstable_createResource
的部分會比較清晰:
export function unstable_createResource(fetch, maybeHashInput) {
const resource = {
read(input) {
...
const result = accessResult(resource, fetch, input, key);
switch (result.status) {
case Pending: {
const suspender = result.value;
throw suspender;
}
case Resolved: {
const value = result.value;
return value;
}
case Rejected: {
const error = result.value;
throw error;
}
default:
// Should be unreachable
return (undefined: any);
}
},
};
return resource;
}
結(jié)合該部分源碼, 進行如下推測:
- 第一次請求沒有緩存, 子組件
throw
一個thenable
對象,Suspense
組件內(nèi)的componentDidCatch
捕獲之, 此時展示Loading
組件; - 當(dāng)
Promise
態(tài)的對象變?yōu)橥瓿蓱B(tài)后, 頁面刷新此時resource.read()
獲取到相應(yīng)完成態(tài)的值; - 之后如果相同參數(shù)的請求, 則走
LRU
緩存算法, 跳過Loading
組件返回結(jié)果(緩存算法見后記);
官方作者是說法如下:
所以說法大致相同, 下面實現(xiàn)一個簡單版的 Suspense
:
class Suspense extends React.Component {
state = {
promise: null
}
componentDidCatch(e) {
if (e instanceof Promise) {
this.setState({
promise: e
}, () => {
e.then(() => {
this.setState({
promise: null
})
})
})
}
}
render() {
const { fallback, children } = this.props
const { promise } = this.state
return <>
{ promise ? fallback : children }
</>
}
}
進行如下調(diào)用
<Suspense fallback={<div>loading...</div>}>
<PromiseThrower />
</Suspense>
let cache = "";
let returnData = cache;
const fetch = () =>
new Promise(resolve => {
setTimeout(() => {
resolve("數(shù)據(jù)加載完畢");
}, 2000);
});
class PromiseThrower extends React.Component {
getData = () => {
const getData = fetch();
getData.then(data => {
returnData = data;
});
if (returnData === cache) {
throw getData;
}
return returnData;
};
render() {
return <>{this.getData()}</>;
}
}
效果調(diào)試可以點擊這里, 在 16.6
版本之后, componentDidCatch
只能捕獲 commit phase
的異常。所以在 16.6
版本之后實現(xiàn)的 <PromiseThrower>
又有一些差異(即將 throw thenable
移到 componentDidMount
中進行)。
ConcurrentMode + Suspense
當(dāng)網(wǎng)速足夠快, 數(shù)據(jù)立馬就獲取到了,此時頁面存在的 Loading
按鈕就顯得有些多余了。(在 suspenseDemo 中有相應(yīng)演示), Suspense
在 Concurrent Mode
下給出了相應(yīng)的解決方案, 其提供了 maxDuration
參數(shù)。用法如下:
<Suspense maxDuration={500} fallback={<Loading />}>
...
</Suspense>
該 Demo 的效果為當(dāng)獲取數(shù)據(jù)的時間大于(是否包含等于還沒確認(rèn)) 500 毫秒, 顯示自定義的 <Loading />
組件, 當(dāng)獲取數(shù)據(jù)的時間小于 500 毫秒, 略過 <Loading>
組件直接展示用戶的數(shù)據(jù)。相關(guān)源碼。
需要注意的是 maxDuration
屬性只有在 Concurrent Mode
下才生效, 可參考源碼中的注釋。在 Sync 模式下, maxDuration
始終為 0。
后記: 緩存算法
-
LRU
算法:Least Recently Used
最近最少使用算法(根據(jù)時間); -
LFU
算法:Least Frequently Used
最近最少使用算法(根據(jù)次數(shù));
若數(shù)據(jù)的長度限定是 3, 訪問順序為 set(2,2),set(1,1),get(2),get(1),get(2),set(3,3),set(4,4)
, 則根據(jù) LRU
算法刪除的是 (3, 3)
, 根據(jù) LFU
算法刪除的是 (1, 1)
。
react-cache
采用的是 LRU
算法。
相關(guān)資料
- suspenseDemo: 文字相關(guān)案例都集成在該 demo 中
-
Releasing Suspense:
Suspense
開發(fā)進度 - the suspense is killing redux