简体   繁体   English

使用 map 后,如何限制和插入从 API 获取请求返回的结果的条件

[英]How can I limit and insert conditions on results returned from API fetch request after using map

I am using Fetch with an API after it returns a 1000 objects I want to render only the first 4 or the values with the highest value在返回 1000 个对象后,我将 Fetch 与 API 一起使用,我只想渲染前 4 个或具有最高值的值

I am using.map on the results but I dont know how to put conditions or limit the.map results?我在结果上使用.map 但我不知道如何设置条件或限制.map 结果?

{NowMovies.map(Movie=>(
     <Col  sm="3">
       <Card key={Movie.id}className='Now_Playing' body>
         <CardImg top width="100%" src={`https://image.tmdb.org/t/p/w200${Movie.poster_path}`}
         alt=""/>
         <CardTitle className='title' >{Movie.title}</CardTitle>
         <CardText className='Text'>Rating:{Movie.vote_average}</CardText>
         <Link to={'/movie/' + Movie.id } > <Button color="danger">Visit</Button>{' '}
</Link>
       </Card>
     </Col>```

I'm not sure what you mean with or the values with the highest value , though if you want to take only 4 elements from your array you can use slice .我不确定您的意思or the values with the highest value ,但如果您只想从数组中获取 4 个元素,您可以使用slice slice can work as a "limit" if you pass 0 as a first argument and number of items you want to obtains as a second argument.如果您将 0 作为第一个参数传递,并且您想要获得的项目数作为第二个参数传递,则slice可以用作“限制”。 eg例如

let arr = [1,2,3,4,5]
arr.slice(0, 4) // [1,2,3,4]

// if you want to get your items starting from specific position:
arr.slice(1, 5) // [2,3,4,5]

{NowMovies.slice(0,4).map(Movie=>(
     <Col  sm="3">
       <Card key={Movie.id}className='Now_Playing' body>
         <CardImg top width="100%" src={`https://image.tmdb.org/t/p/w200${Movie.poster_path}`}
         alt=""/>
         <CardTitle className='title' >{Movie.title}</CardTitle>
         <CardText className='Text'>Rating:{Movie.vote_average}</CardText>
         <Link to={'/movie/' + Movie.id } > <Button color="danger">Visit</Button>{' '}
</Link>
       </Card>
     </Col>)}

 const NowMovies = []; const MAX_RATING = 10; // This is just a sample JSON array with random ratings between 1-10 in this example for (let i = 0; i < 20; i++) { NowMovies.push({ index: i, rating: Math.floor(Math.random() * MAX_RATING + 1) }); } // This is how you sort your array in descending order by rating, and then return the first N results. 5 in this case. const sortedArray = NowMovies.sort((a, b) => b.rating - a.rating).slice(0, 5); console.log(sortedArray);

You need to write a custom sort method to define how you want to sort your array, like this ^您需要编写一个自定义排序方法来定义您希望如何对数组进行排序,就像这样 ^

Then you can slice to return the first N results.然后您可以切片以返回前 N 个结果。

After you have modified your array, you can then use the.map to render the JSX.修改数组后,您可以使用 .map 来渲染 JSX。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM