You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JS中使用map函数渲染堡垒之夜API返回JSON商品数据的实现方法

第一步 修正状态初始值

你原来的items状态用来存储接口返回的商品数组,初始值不能设为空字符串,要改为空数组,避免后续调用map方法时报错。

第二步 新增渲染逻辑

在页面标题下方加入数组遍历逻辑,按照接口返回的字段嵌套规则取出你需要的5个字段渲染即可,注意每个遍历项要加唯一key属性,同时可以加加载提示、空数据提示优化体验。

完整实现代码如下:

import { useState, useEffect } from 'react';

export default function App() {
  // 初始值改为空数组
  const [items, setItems] = useState([]);
  // 新增加载状态优化体验
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const url = 'https://fortnite-api.theapinetwork.com/store/get';

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        setItems(json.data);
      } catch (error) {
        console.log('error', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  // 加载中状态展示
  if (loading) return <div style={{textAlign: 'center', marginTop: '2rem'}}>加载中...</div>

  return (
    <div style={{maxWidth: '1200px', margin: '0 auto', padding: '0 1rem'}}>
      <center>
        <h1>Virtual Fortnite Store</h1>
      </center>
      {/* 遍历渲染商品列表 */}
      <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '1.5rem', marginTop: '2rem'}}>
        {items.map(goods => {
          const itemInfo = goods.item;
          return (
            <div key={itemInfo.id} style={{border: '1px solid #e5e7eb', borderRadius: '8px', padding: '1rem'}}>
              <h3>{itemInfo.name}</h3>
              <img 
                src={itemInfo.images.icon} 
                alt={itemInfo.name} 
                style={{width: '100%', height: '200px', objectFit: 'contain', margin: '1rem 0'}}
              />
              <p><strong>类型:</strong>{itemInfo.type.name}</p>
              <p><strong>稀有度:</strong>{itemInfo.rarity.name}</p>
              <p><strong>描述:</strong>{itemInfo.description}</p>
            </div>
          )
        })}
      </div>
      {/* 空数据提示 */}
      {items.length === 0 && !loading && <div style={{textAlign: 'center', marginTop: '2rem'}}>暂无在售商品</div>}
    </div>
  );
}

字段取值对应逻辑说明:

  • 名称:goods.item.name
  • 图片:示例取的是图标尺寸资源goods.item.images.icon,如果需要更大的展示图可以替换为goods.item.images.featured
  • 类型:goods.item.type.name
  • 稀有度:goods.item.rarity.name
  • 描述:goods.item.description

内容的提问来源于stack exchange,提问作者Umer Arif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:15:03