React 递归动态 import 组件使用 Promise 的问题 ?
- 现在的问题是子组件并没有加载,但是也没报错,有点绕不出来了
function build(page_list: any[]){
return page_list.map((v: any) => {
return import(`./control/${v.component}`).then(module => {
let child: any[] = []
if( v.children ){
let promises = build(v.children)
Promise.all(promises).then(aaa => child = aaa)
}
const ppp = child.length == 0 ? { title_str: "c" } :{ title_str: "c", children: child }
return <module.default key={v.type} {...ppp}></module.default>
});
})
}
回复
1个回答

test
2024-07-03
你这 Promise.all 也没等待执行完,下面 child.length 肯定始终都是 0。
async function build(page_list: any[]){
return await Promise.all(page_list.map(async (v: any) => {
const module = await import(`./control/${v.component}`);
let child: any[] = [];
if (v.children){
let promises = build(v.children);
child = await Promise.all(promises); // 等待
}
const ppp = child.length == 0 ? { title_str: "c" } :{ title_str: "c", children: child };
return <module.default key={v.type} {...ppp}></module.default>;
}));
}
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容