限制.map循环中的项目 [英] Limit items in a .map loop

查看:54
本文介绍了限制.map循环中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下如何将我的.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆