首页 > 解决方案 > 如何显示从获取请求中存储的数据?

问题描述

所以我提出了一个获取请求并将数据存储到一个常量中。我无法访问数据以显示它。

const [itemDetails, setItemDetails] = useState([]);

这是存储在 itemDetails 中的数据结构,我不知道如何显示它。

item:
customerCount: 0
itemCatName: "Furniture - Photos/Paintings/Prints"
itemCost: 21.96
itemDescription: "Removable and repositionable with no sticky residue. Perfect for nurseries, apartments, dorm rooms, and businesses. Wall decal stickers are mess-free, no paint, no glue/paste, no residue."
itemID: 6
itemImage: "/Images/I/51vJQpTLP7L._AC_.jpg"
itemName: "Golf Cart Seniors Isolated Peel and Stick Wall Decals "
unitsSold: 0

customerList: Array(197)
[0 … 197]
0: {customerName: 'Joel Amess', email: 'immamess@gmail.com', primaryPh: '491592807', secondaryPh: null, addressLine1: '51 Prince Street', …}
1: {customerName: 'Jack Schlink', email: 'jackschlink@outlook.com', primaryPh: '0420194047', secondaryPh: null, addressLine1: '34 Round Drive', …}
2: {customerName: 'Jett Freeleagus', email: 'jettfree@gmail.com', primaryPh: '0489847578', secondaryPh: null, addressLine1: '48 Magnolia Drive', …}
3: {customerName: 'Brock Mills', email: 'bmills@gmail.com', primaryPh: '0488806371', secondaryPh: null, addressLine1: '13 Taylor Street', …}
4: {customerName: 'Koby Wiedermann', email: 'koby@gmail.com', primaryPh: '0420029236', secondaryPh: null, addressLine1: '36 Reynolds Road', …}
5: {customerName: 'Eve Coane', email: 'eevee@gmail.com', primaryPh: '0489973669', secondaryPh: null, addressLine1: '22 SWestern Australianston Street', …}

任何帮助将不胜感激

编辑:这是我试图运行的代码,但它给了我 itemDetails.map 不是函数。itemDetails 具有所有正确的数据,我只是无法显示它...

function ItemDetails() {
  //variable to store data passes from handlePageChange
  const location = useLocation();
  const itemID = location.state.itemID;
  const year = location.state.year;
  const [itemDetails, setItemDetails] = useState([]);
  console.log(itemDetails);


  useEffect(() => {
    const fetchItemDetails = async () => {
      if(year != null && itemID != null){
        try {
          const response = await fetch(`http://localhost:56384/api/RecallDetail?itemID=${itemID}&year=${year}`);
          setItemDetails(await response.json());
        } catch (error) {
          console.log('Failed to fetch from Amazon DB', error);
        }
      } else {
        try {
          const response = await fetch(`http://localhost:56384/api/RecallDetail?itemID=${itemID}`);
          setItemDetails(await response.json());
        } catch (error) {
          console.log('Failed to fetch from Amazon DB', error);
        }
      }   
    };
    fetchItemDetails();
  }, []);

  return (  
    <div>
    <div>
    <h1>Recall Information</h1>
    <p>Product:</p>
    <p>Unit Cost:</p>
    <p>Description</p>
    </div>
    <div>
      <table>
      <thead>
          <tr>
          <th>Customer Name</th>
          <th>Contact Details</th>
          <th>Addrress Line</th>
          <th>Total Cost</th>
          <th>Units Sold</th>
          </tr>
        </thead>
        <tbody>
        {itemDetails.map(item => {
                return (
                    <tr >
                    <td>{ item.customerList.customerName }</td>
                    <td>{ item.customerList.email }</td>
                    <td>{ item.customerList.addressLine1 }</td>
                    <td>${ item.customerList.totalCost }</td>
                    <td>{ item.customerList.unitsSold}</td>
                    </tr>
                );
                })}
            </tbody>


      </table>
    </div>

    <NavLink to="/" activeClassName="active">
        Go Back
    </NavLink>
    </div>
  );
}

标签: reactjs

解决方案


您可以映射itemDetails数组,然后为每个项目返回一些 HTML 元素。

import { useEffect } from 'react'

const SomeComponent = () => {
    const [itemDetails, setItemDetails] = useState([]);

    useEffect(() => {
        // Do the fetching and setItemDetails here...
    });

    return (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
            {itemDetails.map((item) => (
                <span>{item.customerName}</span>
            ))}
        </div>
    );
};

map方法根据提供的回调函数返回的项目创建一个数组。所以这里我们只是直接创建一个在 div 内渲染的 span 元素数组。


推荐阅读