javascript - 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"
}
}
谢谢 !
解决方案
您可以尝试添加import React, {useState, useEffect} from 'react
.
推荐阅读
- php - Laravel 6 - 表变空后唯一的自定义ID不会增加
- python-3.x - 麻烦创建测试/培训功能以对少数群体进行过度采样
- javascript - 通过 props 的调度动作最终达到下一个 js 中超出的最大深度
- php - laravel - 试图从获取的集合中删除项目
- c - printf中函数的评估顺序是什么
- python - 代码结束时在 Python 中再次启动函数
- mysql - Mysql - 基于搜索表单在表之间传输数据
- drupal-7 - 在 Drupal 7 Tpl 文件中使用 db_select 的最佳方法是什么?
- android - 在 Kotlin 中将可变的实时数据解析为数组
- mysql - 使用前 2 个条目中的值向表中添加移动平均列