Encountered the problem of being unable to access the data.json file and perform new card/component filtering
P粉032977207
2023-08-16 19:28:38
<p>So I have my page set up to get the id from the previous page. If I click on image 4 it shows the url (/Food/4) and so on. So I got the correct information from the previous page. Now the problem I have is using fetch to get my data.json file, get the information from the json and then render the information on the page based on the id. So if I click on image 4 and pass the id to my new page, I want to display the data for image 4 from the json file. I've tried several different fetch settings and even axios settings but I'm completely at a loss. Do I need to implement useParams? params.id? Thanks! </p>
<pre class="brush:php;toolbar:false;">import React, { useState, useEffect } from 'react'
import { Link, useParams } from 'react-router-dom'
import data from './data.json'
export default function Foodinfo() {
const params = useParams()
const [item, setItem] = useState();
useEffect(() => {
fetch('/data.json')
.then(response => response.json())
.then(data => console.log(data));
})
return (
<div>
<h1>Food Info</h1>
<img src={item.pic} />
<Link to="/">
<button>Menu</button>
</Link>
</div>
)
}</pre>
Access data.json for filtering
It looks like you want to load an item from a
JSON file
based on theid
passed via the URL.You have imported the
data.json
file directly into your component, so there is no need to usefetch
oraxios
to request it. It already exists in the component as variabledata
. Therefore, you can filter the data based on theid
parameter obtained from the URL, and then use the related object to set theitem
status.This is how you should update the
Foodinfo
component to resolve your issue:useParams
to get theid
from the URL.id
as an integer becauseparams.id
will be astring type
and the data in theJSON file
Possibly use a number as ID.item
that is the same as theid
in thedata array
.setItem
function to set thisitem
to the item state.Adjusted code: