[英]retun values in function of array.map in react
Using React JSX, I have an array levels
which can contain arrays of one or more of the levels with a name, for example: one
, two
and three
.使用 React JSX,我有一个数组
levels
,它可以包含一个或多个带有名称的级别的数组,例如: one
、 two
和three
。 In my render function I can call {renderLevels}
which renders all levels separated by a comma.在我的渲染函数中,我可以调用
{renderLevels}
来渲染由逗号分隔的所有级别。
This works:这有效:
const renderLevels = levels.map((item, index) => {
return (
<Fragment key={index}>
{(index ? ' & ' : '')} {item.name}
</Fragment>
)
}
);
In case all levels are present I want to render 'all levels', instead of the comma separated list.如果所有级别都存在,我想呈现“所有级别”,而不是逗号分隔的列表。 In all other cases I want the list.
在所有其他情况下,我想要列表。 So I change my code.
所以我改变了我的代码。
This does not work:这不起作用:
const renderLevels = () => {
if (levels.length === 3) {
return (
'all levels'
)
}
levels.map((item, index) => {
return (
<Fragment key={index}>
{(index ? ' & ' : '')} {item.name}
</Fragment>
)
}
)
};
My const
is now a function I then call with {renderLevels()}
.我的
const
现在是一个函数,然后我用{renderLevels()}
调用。 The problem: the list of item names is no longer returned when there are fewer than 3 levels.问题:当少于 3 个级别时,不再返回项目名称列表。 My if-statement works and
console.log(item.name)
inside .map
does show me the results in case there are fewer than 3 levels.我的 if 语句有效并且
.map
中的console.log(item.name)
确实向我显示了结果,以防少于 3 个级别。 Getting the return values however does not.然而,获取返回值不会。 What am I doing wrong?
我究竟做错了什么?
You are missing return
for the levels.map()
.您缺少
levels.map()
return
。 Currently, you are just returning for the function, inside the if
block but you have not returned anything when that if
is not executed.目前,您只是在
if
块内返回该函数,但在未执行if
时您没有返回任何内容。
const renderLevels = () => {
if (levels.length === 3) {
return (
'all levels'
)
}
return levels.map((item, index) => {
return (
<Fragment key={index}>
{(index ? ' & ' : '')} {item.name}
</Fragment>
)
}
)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.