P粉0200855992023-08-17 18:30:41
It looks like you want to load an item from a JSON file
based on the id
passed via the URL.
You have imported the data.json
file directly into your component, so there is no need to use fetch
or axios
to request it. It already exists in the component as variable data
. Therefore, you can filter the data based on the id
parameter obtained from the URL, and then use the related object to set the item
status.
This is how you should update the Foodinfo
component to resolve your issue:
useParams
to get the id
from the URL. id
as an integer because params.id
will be a string type
and the data in the JSON file
Possibly use a number as ID. item
that is the same as the id
in the data array
. setItem
function to set this item
to the item state. Adjusted code:
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(null); useEffect(() => { // 将URL参数中的id解析为整数类型 const idFromUrl = parseInt(params.id, 10); // 在数据数组中找到与URL中的id匹配的项目 const foundItem = data.find((d) => d.id === idFromUrl); // 将找到的项目设置为状态 setItem(foundItem); }, [params.id]); return ( <div> <h1>食物信息</h1> {/* 在尝试访问其属性之前检查项目是否存在 */} {item ? ( <> <img src={item.pic} alt={item.name} /> <p>{item.name}</p> <p>{item.description}</p> </> ) : ( <p>加载中...</p> )} <Link to="/"> <button>菜单</button> </Link> </div> ); }