前言
最近一直在搞小程序,对react技术比较生疏了,准备重学一下react。在看文档时看到了react提供的lazy、Suspense组件,可以对组件进行懒加载和异常捕获边界的处理。
代码
先看lazy方法的实现
const OtherComponent = React.lazy(() => import('./OtherComponent'))
其实lazy的功能就是异步加载组件,入参就是一个Promise,上面这个段代码就可以对应
const OtherComponent = lazy(new Promise(resolve=>{
setTimeout(()=>{
resolve: {default:<OtherComponent />}
},1000)
}))
接下来实现lazy函数部分
function lazy(fn){
const fetcher = {
status: 'pending',
result: null,
promis: null
}
return function LazyComponent(){
const getData = fn()
fetcher.promis = getData
getData.then((res)=>{
fetcher.status = 'resolve'
fetcher.result = res.default
})
useEfect(()=>{
if(fetcher.status === 'pending'){
throw fetcher
}
},[])
if(fetcher.status === 'resolve'){
return fetch.result
}
return null
}
}
再看Suspense组件,提供了错误捕获,并对错误进行处理,优化用户体验。
简单就是说使用Suspense包裹的子组件如果出现错误,Suspense能捕获到错误并进行处理,
错误处理是Susoense提供fallback属性提供的。
使用示例
<Suspense fallback-{<div>Loding....</div>}>
<OtherComponent />
</Suspense>
简单分析下上述代码的作用,使用Suspense包裹的OtherComponent组件如果有报错,就会展示fallback的内容
下面手动实现一下Suspense
class Suspense extends PureComponent{
state = {
isChildren: true
}
componentDidCatch(info){
this,setState({isChildren: false})
info.promis.then(()=>{
this,setState({isChildren: true
})
}
reder(){
const { fallback, children } = this.props
if(this.state.isChildren){
return children
}
return fallback
}
}
结尾
到此简版的lazy、Suspense功能实现就完成了,如有错误还请指正!或有更好的实现思路,希望能和大家多多交流。