在.map 循环中限制项

例如,我想问一下,如何将 .map循环限制为5个项目,因为目前当我访问一个 api 时,它返回20个项目。但我只想显示5个。我发现大多数情况下,它只是遍历对象数组中的所有循环,而不是将其限制在一些条目中。

注意: 我对 API 没有控制权,因为我只是在使用 animedb API

这是我的密码:

var film = this.props.data.map((item) => {
return <FilmItem key={item.id} film={item} />
});


return film;
116090 次浏览

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;

If you do not need the original array anymore, you could mutate the array by setting the length to 5 and iterate them.

You could use filter() as well

var film = this.props.data.filter((item, idx) => idx < 5).map(item => {
return <FilmItem key={item.id} film={item} />
});


return film;

If you are using a functional component. you can try this:

<p>const [film, setFilm] = useState([])</p>


<i>// Fetch data from API</i>


<p>useEffect(() =>{...})</p>


var fiveFilm = film.slice(0,5)

in your return function:

you can map using:

{fiveFilm.map(item => <p>{item.name}<p>)}

You can also limit it by passing a second argument to a map() callback, which would be an index of an item in the loop.

const film = this.props.data?.map(
(item, index) =>
index < 5 && ( // <= only 5 items
<FilmItem
key={item.id}
film={item}
/>
)
);


return film;

However, you probably should stick to Nina's answer unless you really need some elegancy in your code. Since I'm guessing my answer would be slower performance-wise.

References:

  1. MDN: map() syntax
  2. Optional Chaining