简体   繁体   English

使用 axios 从本地 JSON 文件中获取数据并显示数据

[英]Fetching data from local JSON file using axios and displaying data

This is a local JSON file I wrote.这是我写的本地JSON文件。

{ "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.我获取了数据并解决了它,当我调用 console.log(response.data) 时,我确实得到了 JSON 对象,但是当我想映射它时,它向我显示了一个错误,photos.map 不起作用。

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 .我相信你缺少一个data The response from the axios call will contain the payload (your JSON file) in data , ie, response.data .response从Axios公司的呼叫将包含在有效载荷(您的JSON文件) data ,即, response.data However, that is an object (which has no map function).但是,这是一个对象(没有map功能)。 I believe you are after the array in your own data field, so try:我相信您在自己的data字段中寻找数组,因此请尝试:

            setPhotos(response.data.data)

If your json file contains a data field as an array, you need to call如果您的 json 文件包含一个data字段作为数组,则需要调用

setPhotos(response.data.data);

Otherwise, try to use JSON.parse() (even if I know axios automatically parse json as object, but you never know)否则,尝试使用JSON.parse() (即使我知道 axios 会自动将 json 解析为对象,但您永远不知道)

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

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