慕勒3428872
2022-01-07 20:44:36
我的問(wèn)題是關(guān)于如何部分迭代 React JSX 中的數(shù)組。我不想調(diào)用 .map 并遍歷 profile.categories 中的所有項(xiàng)目,而只想顯示數(shù)組中的前五個(gè)項(xiàng)目。我目前有以下代碼:<div className="categories"> {profile.categories.map(category => ( <div className="profile-categories" style={{ float: "left" }} > {category} </div> ))} </div>
2 回答

慕哥6287543
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊
直接在 profile.categories 上使用 slice,如下所示:
<div className="categories">
{profile.categories.slice(0, 5).map(category => (
<div
className="profile-categories"
style={{ float: "left" }}
>
{category}
</div>
))}
</div>

慕標(biāo)5832272
TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
只需將切片與地圖一起使用:
profile.categories.slice(0, 5).map(...)
您還可以添加方法來(lái)獲取組件中的一些類別計(jì)數(shù):
getFirst(count) {
return profile.categories.slice(0, count);
}
// and then in render:
this.getFirst(5).map(...)
添加回答
舉報(bào)
0/150
提交
取消