限制.map循环中的项目 [英] Limit items in a .map loop
问题描述
我想问一下如何将我的.map
循环限制为5个项目,因为当前访问api时它返回20个项目.但我只想显示5.大多数情况下,我发现只是循环遍历整个对象数组,而不是将其限制为多个项目.
I would like to ask how can I limit my .map
loop for example to a 5 items only because currently when I access an api it returns 20 items. but I want to display only 5. Mostly that I found is just looping all throughout the array of objects and not limiting it to a number of items.
注意:我无法控制API,因为我只是使用moviedb api
Note: I have no control on the API because I'm just using the moviedb api
这是我的代码:
var film = this.props.data.map((item) => {
return <FilmItem key={item.id} film={item} />
});
return film;
推荐答案
You could use Array#slice
and take only the elements you need.
var film = this.props.data.slice(0, 5).map((item) => {
return <FilmItem key={item.id} film={item} />
});
return film;
如果不再保留原始数组,则可以将长度设置为5
的数组进行变异,然后进行迭代.
If you do not neet the original array anymore, you could mutate the array with seting length to 5
and iterate then.
这篇关于限制.map循环中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!