【问题标题】:React.js - Axios fetching on .json file. Front - endReact.js - Axios 获取 .json 文件。前端
【发布时间】:2021-06-01 13:22:06
【问题描述】:

所以我要做的是使用 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"
  }
}

谢谢!

【问题讨论】:

    标签: javascript json reactjs axios react-hooks


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您使用 axios 是否有特定原因?您可以只使用 fetch 模块来做到这一点

      https://www.pluralsight.com/guides/fetch-data-from-a-json-file-in-a-react-app

      【讨论】:

      • Axios 对我来说比 fetch 更清楚。但是谢谢你=)
      【解决方案3】:

      我很困惑您为什么要使用 axios 来执行此操作。 import 文件似乎更自然并将其设置为 groundNames 的默认值(而不是您现在使用的空数组)。

      或者只使用原始值,因为您的代码不会修改数组。

      【讨论】:

      • 谢谢它有效。但是如果不指定地面编号,我将无法检索数据。 ` lang-js return(

        Hello world!

          {groundNames.map((id) => (
        • {id.ground1. groundName}
        • ))}
        )`
      猜你喜欢
      • 1970-01-01
      • 2020-10-22
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 2017-09-28
      相关资源
      最近更新 更多