所以我遇到了这个问题。我正在尝试从我的项目中获取本地json文件。json文件存储在src文件夹中。
这是我的json文件
[
{
"name": "Sunsssset Beach",
"email": "[email protected]",
"image": "https://images.unsplash.com/photo-1439130490301-25e322d88054?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1489&q=80",
"price": 85,
"maxGuests": 18,
"lat": 60.393388,
"lng": 5.22872,
"description": "Get ready for some amazing sunsets as you sip a cocktail and watch dolphins play in the harbour below.",
"selfCatering": true,
"createdAt": "2020-09-04T09:07:10.367Z",
"id": "5f5203bedc17b0a4b302f211"
},
{
"name": "The Hideaway",
"email": "[email protected]",
"image": "https://images.unsplash.com/photo-1551906993-c8b38a6ab201?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=666&q=80",
"price": 70,
"maxGuests": 2,
"lat": 60.425168,
"lng": 5.358141,
"description": "This secluded wilderness cabin is the perfect spot for a restful and cosy getaway.",
"selfCatering": true,
"createdAt": "2020-09-04T09:07:10.370Z",
"id": "5f5203bedc17b0a4b302f213"
},
{
"name": "Rest Easy",
"email": "[email protected]",
"image": "https://images.unsplash.com/photo-1512552288940-3a300922a275?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=751&q=80",
"price": 120,
"maxGuests": 14,
"lat": 60.396779,
"lng": 5.235602,
"description": "Need some time off from your busy life to relax and unwind? Choose Rest Easy for the complete relaxation experience you desire.",
"selfCatering": false,
"createdAt": "2020-09-04T09:07:10.370Z",
"id": "5f5203bedc17b0a4b302f212"
}
]
这是我的项目文件
function Establishment() {
const [establishment, setEstablishment] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("jsonfile")
.then((response) => {
// check if response returns ok
if (response.ok) {
return response.json();
} else {
setErrorHandle(true);
}
})
.then((data) => {
setEstablishment(data);
})
.catch((err) => {
console.log(err);
setErrorHandle(true);
})
.finally(() => setLoading(false));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
现在,我希望能够按一个按钮来显示所有这些项目,并且通过单击一个项目,它应该只在另一个页面中显示该项目。我怎么做?
让我知道您是否还需要解决此问题:)
首先,如果JSON数据位于文件系统的本地文件中,则无需 获取或axios
为什么不使用Axios或Fetch?
Axios或Fetch用于获取数据或将数据发布到服务器中。在本例中,我们读取本地文件夹文件,以便使用map()。
注意:最重要的是在使用Axios和Fetch时,我们需要强制使用URL参数
现在您要做的是:
1.首先将文件导入到要使用的位置:
import data from "../static/data/myData.json";
2.现在,您要映射该Json文件:
<div>
{
data.map(myData, index)=>{
return <div key={myData.id}>
<h1>{myData.name}</h1>
<h3>{myData.email}</h3>
</div>
}
}
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句