简体   繁体   中英

Fetching data from local JSON file using axios and displaying data

This is a local JSON file I wrote.

{ "data":[
    {
    "photo": "https://source.unsplash.com/aZjw7xI3QAA/1144x763",
    "caption": "Viñales, Pinar del Río, Cuba",
    "subcaption": "Photo by Simon Matzinger on Unsplash",
    "thumbnail": "https://source.unsplash.com/aZjw7xI3QAA/100x67",
    }, 
    {
    "photo": "https://source.unsplash.com/c77MgFOt7e0/1144x763",
    "caption": "La Habana, Cuba",
    "subcaption": "Photo by Gerardo Sanchez on Unsplash",
    "thumbnail": "https://source.unsplash.com/c77MgFOt7e0/100x67",
    },
    {
    "photo": "https://source.unsplash.com/QdBHnkBdu4g/1144x763",
    "caption": "Woman smoking a tobacco",
    "subcaption": "Photo by Hannah Cauhepe on Unsplash",
    "thumbnail": "https://source.unsplash.com/QdBHnkBdu4g/100x67",
    }
]
}

and I don't understand why can't I map value after resolving. I fetched data and resolved it, and when I call console.log(response.data) I do get the JSON object, but when I want to map it, it show me an error that photos.map isn't function.

import React from 'react'
import { useState, useEffect } from 'react'
import axios from 'axios'

function FetchingData() {
    const [photos, setPhotos] = useState([]);

    useEffect(()=>{
        axios.get('photos.json')
        .then(response => {
            console.log(response)
            setPhotos(response.data)
        })
    })

    return (
        <div>
            <ul>
               {photos.map(photos => (<li>{photos.photo}</li>)
               )}
            </ul>
        </div>
    )
}

export default FetchingData

I believe you are missing a data . The response from the axios call will contain the payload (your JSON file) in data , ie, response.data . However, that is an object (which has no map function). I believe you are after the array in your own data field, so try:

            setPhotos(response.data.data)

If your json file contains a data field as an array, you need to call

setPhotos(response.data.data);

Otherwise, try to use JSON.parse() (even if I know axios automatically parse json as object, but you never know)

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