React useParams 在进入页面时给出空对象

2023-12-09

我正在做个人React.js项目。我有以下问题useParams。单击导航栏后无法显示地图项目​​。它进入页面,但无法在屏幕上显示。它在屏幕上显示一个空物体。这是ItemContainer我在哪里定义了useParams我认为代码有错误:

import { useEffect, useState } from "react";

import ItemDetails from "../Itemdetails";
import { useParams } from "react-router-dom";

const ItemContainer = () => {
  const [venue, setVenue] = useState({});
  const { raceId } = useParams();

  useEffect(() => {
    fetch("https://www.betright.com.au/api/racing/todaysracing")
      .then((res) => {
        return res.json();
      })
      .then(
        (data) => {
            setVenue(data);
          console.log("data useEffect", data);
        },
        (err) => {
          return console.error(err);
        }
      );
  }, []);
  console.log("venue container", {venue});

  const para = Object.keys(venue).find((findKey) => findKey === raceId);
  console.log('para', para)

  return (
      <ItemDetails key={para} venue={venue} />
  );
};

export default ItemContainer;

这是ItemDetails我想在哪里显示该项目:

const ItemDetails = ({ venue }) => {
    console.log('venue itemDetails', venue)
    return (
        <> 
        {venue.slice(0, 5).map(races => (
            <>
            <p>{races.Venue}</p>
            <p>Race Number: {races.Race1?.RaceNumber}</p>
            </>
        ))}
        </>
    );
}
 
export default ItemDetails;

这是导航栏:

import { useEffect, useState } from "react";

import { NavLink } from "react-router-dom";
import styles from './Navbar.module.css';

const Navbar = () => {
    const [result, setResult] = useState([]);

    useEffect(() => {
      fetch("https://www.betright.com.au/api/racing/todaysracing")
        .then((res) => {
          return res.json();
        })
        .then(
          (data) => {
            setResult(data);
            console.log("data useEffect", data);
          },
          (err) => {
            return console.error(err);
          }
        );
    }, []);
    console.log("result of Navbar", result);
    
    return (
        <>            
            <div className={styles.navbarContainer}>
                <NavLink to='./races' 
                className={styles.navbarHome} 
                style={({ isActive }) => ({
                  color: isActive ? '#fff' : '#f4f4f4',
                  background: isActive ? '#7600dc' : '#7600dc',
                })}>Home</NavLink>
                {Object.entries(result).map(([key, value]) => (
                    <div className={styles.navbarItems} key={key}>
                        {value.slice(0, 1).map((i, race) => (
                            <NavLink 
                                key={i}
                                to={`/race/${key}`}
                                style={({ isActive }) => ({
                                    color: isActive ? '#fff' : '#d3d3d3',
                                    background: isActive ? '#7600dc' : '#7600dc',
                                    textDecoration: isActive ? 'none' : 'none'
                                    })}>{key}</NavLink>
                        ))}                            
                    </div>                                  
                ))}
            </div>
        </>
    );
}
 
export default Navbar;

这是App.js

const App = () => {
  return (
    <>
        <Router>
            <Navbar />
            <Routes>
                <Route path='/races' element={<Home />} />
                <Route path="/" element={<Navigate replace to="/races" />} />
                <Route path="/race/:raceId" element={<ItemContainer />} />
            </Routes> 
        </Router>
        
    </>
  )
}

这是一个link到codesandbox 包含整个代码。

UPDATE

这是数据的模拟。 API 的原始值都有不同的值,只有 Throughbred、Harness 和 Greyhound 的键对于已找到的 useParams 来说是通用的。这是一个新的链接整个代码加上模拟的数据。您还可以在下面找到模拟数据:

    const data = {
      Throughbred: [
        {
            VenueID: 674,
            Venue: "Santa Anita Park",
            Race1: {
              EventTypeId: 1,
              EventId: 6177745,
              VenueId: 0,
              Venue: null,
              CountryCode: null,
              RaceNumber: 6,
              AdvertisedStartTime: "/Date(1641036900000)/",
              ResultStatusId: 0,
              SecondsToJump: 609,
              HasFixedMarkets: false,
              IsOpenForBetting: false,
              MarketShortcuts: null,
              Results: null,
              MasterCategoryName: null,
              EventName: null,
            },
            CountryCode: "USA",
            MasterCategoryName: "Overseas-Racing",
          },
          {
            VenueID: 674,
            Venue: "Santa Anita Park",
            Race1: {
              EventTypeId: 1,
              EventId: 6177745,
              VenueId: 0,
              Venue: null,
              CountryCode: null,
              RaceNumber: 6,
              AdvertisedStartTime: "/Date(1641036900000)/",
              ResultStatusId: 0,
              SecondsToJump: 609,
              HasFixedMarkets: false,
              IsOpenForBetting: false,
              MarketShortcuts: null,
              Results: null,
              MasterCategoryName: null,
              EventName: null,
            },
            CountryCode: "USA",
            MasterCategoryName: "Overseas-Racing",
          }
        ],
    
      Harness: [{
        VenueID: 674,
        Venue: "Santa Anita Park",
        Race1: {
          EventTypeId: 1,
          EventId: 6177745,
          VenueId: 0,
          Venue: null,
          CountryCode: null,
          RaceNumber: 6,
          AdvertisedStartTime: "/Date(1641036900000)/",
          ResultStatusId: 0,
          SecondsToJump: 609,
          HasFixedMarkets: false,
          IsOpenForBetting: false,
          MarketShortcuts: null,
          Results: null,
          MasterCategoryName: null,
          EventName: null,
        },
        CountryCode: "USA",
        MasterCategoryName: "Overseas-Racing",
      },
      {
        VenueID: 674,
        Venue: "Santa Anita Park",
        Race1: {
          EventTypeId: 1,
          EventId: 6177745,
          VenueId: 0,
          Venue: null,
          CountryCode: null,
          RaceNumber: 6,
          AdvertisedStartTime: "/Date(1641036900000)/",
          ResultStatusId: 0,
          SecondsToJump: 609,
          HasFixedMarkets: false,
          IsOpenForBetting: false,
          MarketShortcuts: null,
          Results: null,
          MasterCategoryName: null,
          EventName: null,
        },
        CountryCode: "USA",
        MasterCategoryName: "Overseas-Racing",
      }
    ],
      Greyhound: [
        {
            VenueID: 674,
            Venue: "Santa Anita Park",
            Race1: {
              EventTypeId: 1,
              EventId: 6177745,
              VenueId: 0,
              Venue: null,
              CountryCode: null,
              RaceNumber: 6,
              AdvertisedStartTime: "/Date(1641036900000)/",
              ResultStatusId: 0,
              SecondsToJump: 609,
              HasFixedMarkets: false,
              IsOpenForBetting: false,
              MarketShortcuts: null,
              Results: null,
              MasterCategoryName: null,
              EventName: null,
            },
            CountryCode: "USA",
            MasterCategoryName: "Overseas-Racing",
          },
          {
            VenueID: 674,
            Venue: "Santa Anita Park",
            Race1: {
              EventTypeId: 1,
              EventId: 6177745,
              VenueId: 0,
              Venue: null,
              CountryCode: null,
              RaceNumber: 6,
              AdvertisedStartTime: "/Date(1641036900000)/",
              ResultStatusId: 0,
              SecondsToJump: 609,
              HasFixedMarkets: false,
              IsOpenForBetting: false,
              MarketShortcuts: null,
              Results: null,
              MasterCategoryName: null,
              EventName: null,
            },
            CountryCode: "USA",
            MasterCategoryName: "Overseas-Racing",
          }
        ]
}
export default data;

Also, this is a screenshot of the console.log(result) enter image description here


您在处理响应数据的方式上遇到了一些问题。

Navbar

数据是一个对象,其中每个属性都是一个键(种族分类?),其值为场地数组。只需将键映射到链接即可。

{Object.keys(result).map((key) => (
  <div className={styles.navbarItems} key={key}>
    <NavLink
      to={`/race/${key}`}
      style={({ isActive }) => ({
        color: isActive ? "#fff" : "#d3d3d3",
        background: isActive ? "#7600dc" : "#7600dc",
        textDecoration: isActive ? "none" : "none"
      })}
    >
      {key}
    </NavLink>
  </div>
))}

物品容器

假设fetch功能正确并且venues状态已更新为正确的值,这里的问题是您仅搜索键,仅返回键而不是数组值。在这里您可以简单地使用raceId作为访问场地数组的动态键。

const para = venues[raceId] ?? [];

...

return para.map((venue) => <ItemDetails key={venue.VenueID} venue={venue} />);

Edit react-useparams-gives-empty-object-when-goes-to-page

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React useParams 在进入页面时给出空对象 的相关文章

随机推荐