首页 > 解决方案 > React.js - Axios 获取 .json 文件。前端

问题描述

所以我想做的是使用 axios 从我项目根目录的 json 文件中获取一些数据,并将这些数据显示在列表中。我必须使用函数方法和钩子。

所以我已经搜索了如何以这种方式使用 axios。我试图整合它,但最后我没有设法显示列表。我真的不知道缺少什么或我做错了什么?

import  { useState, useEffect } from "react";
import axios from  'axios';

export default function Groundlist() {
    const [groundNames, setgroundNames] = useState([]);
    const [error, setError] = useState('');
    const [isError, setIsError] = useState(false);

    useEffect(() => {
        const fetchData = () => {
            axios
            .get('./../../../UballersGroundsData.json')
            .then((res) =>{ setgroundNames(res.data);})
            .catch(err => { setIsError(!isError); setError({error}) })
        }
        fetchData()
    }, []);

    return(
        <div>
            <h1>Hello world!</h1> 
            <ul>
                {groundNames.map((name, id) => (
                    <li key={id.groundId}>{name.groundName}</li> 
            ))}
            </ul>

        </div>
    )
}

.json 文件的一部分只是为了了解结构

{
  "ground1":{
    "groundId": "2",
    "address": "77-101 Quai Branly, Paris, France",
    "addressLanguage": "fr_FR",
    "basketNumber": "4",
    "city": "Paris",
    "country": "France",
    "gameType": "3x3,4x4,half,full",
    "groundCreatorId": "1",
    "groundDescription": "Il y a 2 terrains : 1 de basket et 1 citystade, (sur lequel il y a basket et foot sur le même terrain)",
    "groundLevel": "advanced,semiPro,pro",
    "groundName": "Bir-Hakeim",
    "groundNumber": "2",
    "groundPhoto": "P1190343.JPG",
    "groundType": "concrete",
    "idGround": "2",
    "lastUpdate": "2018-10-07 21:17:07",
    "latitude": "48.8564",
    "limit": "public",
    "longitude": "2.29074",
    "multisport": "1",
    "net": "2",
    "price": "",
    "roof": "1",
    "status": "validated",
    "transport": "RER C, station Champ de Mars - Tour Eiffel ; métro ligne 6, station Bir-Hakeim"
  }
}

谢谢 !

标签: javascriptjsonreactjsaxiosreact-hooks

解决方案


您可以尝试添加import React, {useState, useEffect} from 'react.


推荐阅读