遍历 JSON 数组,访问输出名称和 Id 以设置类名

Iterating through JSON array, accessing name for output and Id to set className

我正在练习通过获取堡垒之夜即将推出的物品来进行 api 通话。

我正在尝试访问 json 数组中项目的 itemId 和名称,大致如下所示:

data: Array(67)
0: {itemId: "bcc523f5-bef4-44eb-8855-35a1413b669c", lastUpdate: 1617619592, item: {…}}
1: {itemId: "723a761f-fa59-4cfc-92e7-9309a87c5a9e", lastUpdate: 1617585135, item: {…}
}

然后:

0:
item: {name: "Ruby Shadows", description: "Sometimes you gotta go dark.", type: "outfit", rarity: "epic", series: "shadow", …}
itemId: "bcc523f5-bef4-44eb-8855-35a1413b669c"
lastUpdate: 1617619592
__proto__: Object

我正在使用 .map 这样做,但在某些情况下,<h3 key={items.itemId}> 中的对象文字不会 return 期望的结果。 (目前 return 未定义)

整个下午我都在绞尽脑汁。还很陌生。

我的代码:

import './App.css';
import { Link } from 'react-router-dom';

function Shop() {
    useEffect(() => {
        fetchItems();
    },[]);
    
    const [items, setItems] = useState([]);

    let dataArray = [];
    const fetchItems = async () => {
      const data = await fetch('https://fortnite-api.theapinetwork.com/upcoming/get');
      
      const items = await data.json();
      dataArray = items.data;
      setItems(dataArray.map( x => {return x}));
      console.log(items);
    }
   

  return (
    <div id="App">
      <h1>Upcoming Fortnite Items</h1>
      <div>
        {items.map(x => 
        <Link to={`/shop/${items.itemId}`}>
          <h3 key={items.itemId}>
          {x.item.name} 
          </h3>
          </Link>)}       
      </div>
    </div>
  );
}

export default Shop;

感谢您的帮助,谢谢。

编辑:

这是另一个处理其他页面的组件的组件,其中应该输出项目详细信息:(抱歉)

import './App.css';
import { Link } from 'react-router-dom';


function ItemDetail({ match }) {
  /**this puts it into effect */
    useEffect(() => {
        fetchItem();
        console.log(match);
    },[]);
    
    const [item, setItem] = useState([]);

    const fetchItem = async () => {
        const fetchItem = await fetch(`https://fortnite-api.theapinetwork.com/item/get?id={{itemid}}`);
        const item = await fetchItem.json();
    }

  return (
    <div id="App">
      <h1>Item</h1>
    </div>
  );
}

export default ItemDetail;```

问题就在这里:

return (
    <div id="App">
      <h1>Upcoming Fortnite Items</h1>
      <div>
        {items.map(x => 
        <Link to={`/shop/${items.itemId}`}> // <-------  Here 
          <h3 key={items.itemId}> //<-------- Here
          {x.item.name} 
          </h3>
          </Link>)}       
      </div>
    </div>
  );

您需要从每个元素中获取 itemId,现在您正试图从实际数组中获取值,该数组不包含任何字段,因此给您 undefined .

代码应如下所示:

return (
    <div id="App">
      <h1>Upcoming Fortnite Items</h1>
      <div>
        {items.map(x => 
        <Link to={`/shop/${x.itemId}`}>
          <h3 key={x.itemId}>
          {x.item.name} 
          </h3>
          </Link>)}       
      </div>
    </div>
  );