Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

reactjs - Uncaught (in promise) TypeError: images.map is not a function

I'm trying to learn how to fetch data from jsonplaceholder api using axios. I tried to fetch images from https://jsonplaceholder.typicode.com/v1/photos and map it to an img element but I'm getting "Uncaught (in promise) TypeError: images.map is not a function" error. How can I solve this error??

Here is my code enter image description here

import axios from "axios";
import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [images, setImages] = useState([]);

  const getData = async () => {
    const { data: images } = await axios(
      "https://jsonplaceholder.typicode.com/photos"
    );
    setImages({ images });
    console.log(images);
  };

  useEffect(() => {
    getData();
  }, []);
  return (
    <div className="App">
      Populate with imagse from jsonplaceholder
      {images.map((image) => {
        return <img src={image.thumbnailUrl} alt={image.title} />;
      })}
    </div>
  );
}

The solutions given work in codeSandbox. https://codesandbox.io/s/react-json-server-9g7wo?file=/src/VideoCard.js But in the real app is still giving me "Unhandled Rejection (TypeError): Object(...) is not a function" error


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With this:

setImages({ images });

you are setting the images variable to be an object which has one property, images, which is an array, kind of like this:

const imagesForNextRender = {
  images: [
    /* image data */
  ]
};

But you can't .map that. Either extract the images property first (not recommended):

images.images.map(

or, more sensibly, call setImages with the array itself, rather than wrapping it in an object:

const result = await axios("https://jsonplaceholder.typicode.com/photos");
setImages(result.data);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...