官网给出的使用方式是通过import关键字引入组件,进行懒加载
const OtherComponent = React.lazy(() => import('./OtherComponent'));
这种方式适合于明确知道组件的路径。但我要做一个公共组件,使用者不需要知道路径这种细节,只需直接拿来调用。所以我把组件放到了window上:
// 公共组件
const RelateToDs = props => {
return "hello world"
}
export default RelateToDs;
// 放在window上
import RelateToDs from './RelateToDs';
window.commonComponent = RelateToDs;
然后通过React.lazy来调用:
const Hello = React.lazy(async () => {
// 由于 React.lazy要求返回promise,所以加了async关键字
let res = window.commonComponent;
return res;
});
结果报错如下:
说是传入了undefined,打印一下 res:
再打印一下Hello
发现_result是undefined,也就是说没有拿到上面的res。猜测是放res的地方不对,导致组件上没取到。那么问题出在哪呢,再看一遍文档,
就是说要用default!!!
const Hello = React.lazy(async() => {
let res = window.commonComponent;
return {default: res.default || res}; // 关键问题
});
再看一眼Hello是什么样子的
总结
使用React.lazy需要注意两点:
- 返回一个promise, 绝大多数场景都是import("./index"),import返回的本身就是promise。
- 如果不是使用import,记得用default包好再return。