Suspense的意义
划分页面中需要并发渲染的部分,用同步的代码解决异步问题
目前已支持场景
- 配合
React.lazy
实现code spliting
- 请求数据时解决loading问题
- 通过React提供的fetch库
Relay
改造后的异步请求 - 使用react-cache缓存
- 通过React提供的fetch库
- useTransition
- useDeferredvalue
Suspense的实现
通过promise状态实现
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 }
</>
}
}