如何在React Js中使用useNavigation Hooks传递JSON数据?

发布于 2025-01-12 00:04:02 字数 1712 浏览 0 评论 0原文

这是我在应用程序中创建的 Json 文件。

export const Data = [
    {
        id: 1,
        title: "Tilte 1",
        description: "Decription 1 Data",
    },
    {
        id: 2,
        title: "Tilte 2",
        description: "Decription 2 Data",
    }
];

这是我导航的主文件。我使用json文件来显示页面上的所有记录。当我单击所选项目时,它将获取其 id 并导航到另一个页面,在其中我可以获取来自 json 的所选项目的数据。

import React from "react";
import { Data } from "./JSON"
import { useNavigate } from 'react-router-dom'

const Home = () => {
    let naviagte = useNavigate();
    return (
<>


         {Data.map((data, key) => {
            return (
            <div class="card" >
                <div class="card-body">
                    <h5 class="card-title" key={key.id}>{data.title}</h5>
                    <p class="card-text">{data.description}</p>
                    <button onClick={() => naviagte(`/service/${data.id}`)}>{data.title} </button>
                </div>
            </div>
            );
          })}
     </>

    )
}
export default Home;

当我导航到另一个页面时,我想显示有关所选 ID 的所有数据。它只显示 id,不显示所有数据。

import React, {useState, useEffect} from "react";
import { Data } from "../home/JSON"
import { useParams } from "react-router-dom";

const Service = () => {

    const { id } = useParams();

    const [data, setData] =useState('');
    console.log("check", data);
  
     useEffect(() => {
      setData (Data.map((_data) => _data.id === id ))
     }, [id])


    return(
        <>
{id}
{data.title}
{data.description}
        </>
    )
}

export default Service;

请指导我我在这里想念什么。提前致谢

This is my Json file which I created in my app.

export const Data = [
    {
        id: 1,
        title: "Tilte 1",
        description: "Decription 1 Data",
    },
    {
        id: 2,
        title: "Tilte 2",
        description: "Decription 2 Data",
    }
];

This is my main file from where I navigate it. I use json file to display all the records on page. When I click on selected item it will get its id and navigate to another page, where i can get the data of selected item coming from json.

import React from "react";
import { Data } from "./JSON"
import { useNavigate } from 'react-router-dom'

const Home = () => {
    let naviagte = useNavigate();
    return (
<>


         {Data.map((data, key) => {
            return (
            <div class="card" >
                <div class="card-body">
                    <h5 class="card-title" key={key.id}>{data.title}</h5>
                    <p class="card-text">{data.description}</p>
                    <button onClick={() => naviagte(`/service/${data.id}`)}>{data.title} </button>
                </div>
            </div>
            );
          })}
     </>

    )
}
export default Home;

When I navigate to another page where I want to display all data regarding the selected id. It shows only id not all data.

import React, {useState, useEffect} from "react";
import { Data } from "../home/JSON"
import { useParams } from "react-router-dom";

const Service = () => {

    const { id } = useParams();

    const [data, setData] =useState('');
    console.log("check", data);
  
     useEffect(() => {
      setData (Data.map((_data) => _data.id === id ))
     }, [id])


    return(
        <>
{id}
{data.title}
{data.description}
        </>
    )
}

export default Service;

Please guide me what I miss here. Thanks in Advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

满地尘埃落定 2025-01-19 00:04:02

由于您要在这两个位置导入数据,因此您只需通过 id 属性查找数据,而不是将其映射到布尔值。请记住,您的 id 属性是一个数字,但 id 路由参数将是一个字符串,因此您需要将它们转换为兼容类型以实现严格相等( ===) 检查。

示例:

useEffect(() => {
  setData(Data.find((_data) => String(_data.id) === id));
}, [id]);

由于 data 在渲染返回中被视为对象,因此您需要确保保持有效的状态不变性。将初始 data 状态更新为对象,并在更新状态之前检查 Array.prototype.findData 数组返回已定义的对象。

const Service = () => {
  const { id } = useParams();

  const [data, setData] = useState({});
  console.log("check", data);
  
  useEffect(() => {
    const data = Data.find((_data) => String(_data.id) === id);   
    if (data) {
      setData(data);
    }
  }, [id]);

  return (
    <>
      {id}
      {data.title}
      {data.description}
    </>
  );
};

Since you are importing the data in both places you just need to find the data by the id property instead of mapping it to booleans. Keep in mind that your id property is a number but the id route param will be a string, so you will need to convert them to a compatible type for the strict equality (===) check.

Example:

useEffect(() => {
  setData(Data.find((_data) => String(_data.id) === id));
}, [id]);

Since data is treated as an object in the render return you'll want to insure you maintain a valid state invariant. Update the initial data state to be an object, and check that Array.prototype.find returned a defined object from the Data array before updating state.

const Service = () => {
  const { id } = useParams();

  const [data, setData] = useState({});
  console.log("check", data);
  
  useEffect(() => {
    const data = Data.find((_data) => String(_data.id) === id);   
    if (data) {
      setData(data);
    }
  }, [id]);

  return (
    <>
      {id}
      {data.title}
      {data.description}
    </>
  );
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文