React js中的条件渲染 [英] Conditional Rendering in React js
本文介绍了React js中的条件渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在渲染中添加了一个条件,突然它停止显示.这是我正在使用的代码.
I have added a condition in rendering and suddenly it stops displaying. Here is the code am using.
{this.state.sdata.map((sdata, i) =>
{i < 5 &&
<ServiceNavItem key={i} onClick={()=>this.handleSelect(i)}{...sdata} />
}
)
}
我只想显示sdata中的4个项目.任何人都可以帮忙.
I want to display only 4 items from sdata. Anybody please help.
推荐答案
您忘记从 map
正文中返回
元素,以及您需要在 i> = 5 之后为
. array
的所有条目返回null
You forgot to return
the element from map
body, as well as you need to return null
for all the entries of array
after i >= 5.
这样写:
{this.state.sdata.map((sdata, i) => {
if(i < 5)
return <ServiceNavItem key={i} onClick={()=>this.handleSelect(i)}{...sdata} />
return null;
})
}
但是我建议您使用 for循环
而不是 map
创建5个元素.
But i will suggest you to use for loop
instead of map
to create only 5 elements.
如果您想使用 map
,请先使用 切片 并创建包含5个元素的子 array
,然后在其上使用 map
.
If you want to use map
then first use slice and create a sub array
of 5 elements then use map
on that.
赞:
{this.state.sdata.slice(0,5).map((sdata, i) => {
return <ServiceNavItem key={i} onClick={()=>this.handleSelect(i)}{...sdata} />
})}
这篇关于React js中的条件渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文