知识点
模拟理解React.lazy()
+ Suspense
:
// 模拟 Lazy 组件
const Lazy = () => {
// 模拟 ()=> import('index.js') 效果
throw new Promise((resolve) => {
setTimeout(() => {
// 注意:有个 default 属性
resolve({default: '子组件'})
}, 3000);
})
}
// 模拟 Suspense 组件
function Suspense() {
try {
Lazy()
} catch (promise) {
console.log('渲染 fallback')
promise
.then(result => {
/*
只要 promise 状态发生变化,就能触发 then 方法(此时:pending --> fulfilled);
result 就是导入的模块,result.default 就能获取到 index.js 的默认导出值;
这时控制渲染 Suspense 子组件
*/
console.log('渲染完成,加载子组件', result)
})
.catch(error => {
/*
pending --> rejected
*/
console.log('处理异常。。。')
})
}
}
/* 相当于 <Suspense> 组件 */
Suspense()