我有以下代码:
<DetailsBox title={t('catalogPage.componentDetails.specs.used')}>
{component?.projects.map(project => {
projectList?.map(name => {
if (project.id === name.id) {
return (
<Typography variant="body2" gutterBottom classes={{}}>
{`${name.name}`}
</Typography>
);
}
});
})}
</DetailsBox>
我得到了Expected to return a value at the end of arrow function
,我知道它是由匿名函数中的return
引起的,但是如何重构它呢?
编辑:错误已分配至以下行:projectList?.map(name => {
答案 0 :(得分:2)
警告是因为您有时只是从.map
返回某些内容;结果数组当前有时会包含undefined
个元素,其中散布着Typography
个组件。
使用.filter
来过滤不匹配的ID:
<DetailsBox title={t('catalogPage.componentDetails.specs.used')}>
{component?.projects.map(project => (
projectList
?.filter(name => project.id === name.id)
?.map(name => (
<Typography variant="body2" gutterBottom classes={{}}>
{`${name.name}`}
</Typography>
))
))}
</DetailsBox>
或者,如果每对最多只有一个单个匹配项,则更合适的做法是创建一个对象或ID映射到projects
项或projectList
项-这会将计算复杂度从O(n)
降低到O(n ^ 2)
。
答案 1 :(得分:2)
您的父函数未返回值。因此,您需要为隐式return或显式return语句使用括号:
隐含:
<DetailsBox title={t('catalogPage.componentDetails.specs.used')}>
{component?.projects.map(project => (
projectList?.map(name => {
if (project.id === name.id) {
return (
<Typography variant="body2" gutterBottom classes={{}}>
{`${name.name}`}
</Typography>
);
}
));
})}
</DetailsBox>
显式回报:
<DetailsBox title={t('catalogPage.componentDetails.specs.used')}>
{component?.projects.map(project => {
return projectList?.map(name => {
if (project.id === name.id) {
return (
<Typography variant="body2" gutterBottom classes={{}}>
{`${name.name}`}
</Typography>
);
}
})
})}
</DetailsBox>
答案 2 :(得分:0)
尝试
<DetailsBox title={t('catalogPage.componentDetails.specs.used')}>
{component?.projects.map(project => {
return projectList?.map(name => {
if (project.id === name.id) {
return (
<Typography variant="body2" gutterBottom classes={{}}>
{`${name.name}`}
</Typography>
);
}
return null
});
})}
</DetailsBox>