Suspense的意義
劃分頁面中需要并發(fā)渲染的部分,用同步的代碼解決異步問題
目前已支持場景
- 配合
React.lazy
實(shí)現(xiàn)code spliting
- 請(qǐng)求數(shù)據(jù)時(shí)解決loading問題
- 通過React提供的fetch庫
Relay
改造后的異步請(qǐng)求 - 使用react-cache緩存
- 通過React提供的fetch庫
- useTransition
- useDeferredvalue
Suspense的實(shí)現(xiàn)
通過promise狀態(tài)實(shí)現(xiàn)
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 }
</>
}
}