简体   繁体   中英

How to successfully render an array of images from the Nasa Mars Rover api

I'm working on a project that consumes data from the Nasa Mars Rover api and keeps it in a store with Immutable.js store. The data is correctly updated in the store, and i'm able to access the data and print it to the console, but i can't get the images to display.

My functions:

const renderRoverImages = () => {

    const imageGallery = store.get('roverImages');
    console.log(imageGallery);

    const imageGallerySlice = imageGallery.slice(0, 10);
    console.log(imageGallerySlice);


    // const img_src = imageGallerySlice[8].img_src;
    // console.log(img_src);
    if (imageGallerySlice.hasOwnProperty('img_src')) {
        imageGallerySlice.map(
            image => roverImageGallery(image.get('img_src')).join('')
        );
    }
    return `<p class='loading-images'>Loading Images</p>`;

};


const roverImageGallery = (src) =>
  ` <div class='scroll-item'> <img src='${src}' alt='One of the rover latest images'></div>`;

Both the imageGallery and ImageGallerySlice variables print the data i want to the console, but i seem unable to render the images with the logic from there.

The data printed to my console

I'm able to log images to the console with this variable i commented out above that selects by the array index-

// const img_src = imageGallerySlice[8].img_src; // console.log(img_src);

Initially throws an error, but then further down the page i'm able to see the image

Error Rover Image

Otherwise without that line no errors appear in the console, but the second conditional statement renders on the page- "images loading"

Many thanks, Evan

The call to imageGallerySlice.map converts one collection into a new collection. However, the result is never used!

Maybe you wanted or even did write something similar to

return imageGallerySlice.map(
    image => roverImageGallery(image.get('img_src')).join('')
);

This code then brings you to the next issue: An Immutable.js collection's .map does not return an array but a new Immutable.js collection .

So you end up with a collection of react components, which React does not understand.

The solution is to explicitly convert to an array, eg with toArray()

return imageGallerySlice.toArray().map(
    image => roverImageGallery(image.get('img_src')).join('')
);

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