简体   繁体   中英

How can I get the 1st image from each album with an even ID in React using Fetch?

I have an API that returns 5000 images. I want to get the 1st image from each album with an even ID in React using Fetch.

The problem is can't figure out how to filter the data to get the ones with the even IDs and the First Image of the even ID albums.

 import React, {useState, useEffect} from 'react'; // Import Materials from Material-ui import {Grid} from '@material-ui/core'; const Album = () => { const [images, setImages] = useState([]); const [imagesCount, setImagesCount] = useState(10); const api = 'https://jsonplaceholder.typicode.com/photos'; useEffect(() => { fetch(api).then(res => res.json()).then(data => { const filterData = data.filter(x => x.albumId % 2 === 0); for(const url of filterData) { if(url.albumId % 2 === 0) { // How to get only the first even ablumID url of each even albumID? } } setImages(filterData); console.log(filterData); }).catch(err => console.log(err)) }, []); return ( <div> <Grid container spacing={3} alignItems="center"> {images.map((album) => ( <Grid item key={album.id} xs={12} sm={6} md={4}> <img className="albumImg" src={album.url} alt={album.title} /> </Grid> ))} </Grid> </div> ) } export default Album;

As for the first issue, Array.prototype.filter does not mutate the existing array but instead returns a new array with the elements that pass the test, so you need to store that new array in a variable and use that to update your state,

 const api = "https://jsonplaceholder.typicode.com/photos"; fetch(api).then((res) => res.json()).then((data) => { const filterData = data.filter((x) => x.albumId % 2 === 0); console.log("original", data.length); console.log("filtered", filterData.length); }).catch((err) => console.log(err));

As for your second issue, if you want to create a new array with items that have unique albumId s, you could use Array.prototype.reduce to loop through all items and only add those that are not already in the accumulator ,

 const api = "https://jsonplaceholder.typicode.com/photos"; fetch(api).then((res) => res.json()).then((data) => { const filterData = data.filter((x) => x.albumId % 2 === 0); const uniqueItems = filterData.reduce((accumulator, item) => { const isDuplicateItem = accumulator.find( (i) => i.albumId === item.albumId ); // append the item if there's no existing // item in the array with the same `albumId` if (.isDuplicateItem) { return [..,accumulator; item]; } return accumulator, }; []). console,log("uniqueItems". uniqueItems;length). console;log(uniqueItems[0]). console;log(uniqueItems[1]). }).catch((err) => console;log(err));

See more if needed:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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