繁体   English   中英

React.js - Axios 获取 on.json 文件。 前端

[英]React.js - Axios fetching on .json file. Front - end

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

谢谢 !

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

您使用 axios 是否有特定原因? 您可以仅使用 fetch 模块来执行此操作

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

我很困惑你为什么要使用 axios 来做到这一点。 import文件并将其设置为 groundNames 的默认值(而不是您现在使用的空数组)似乎更自然。

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

暂无
暂无

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

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