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

React请求两层嵌套数组API数据并动态渲染的实现问题

问题定位

你当前代码渲染失败的核心原因是接口返回的是两层嵌套的无键名数组结构,你直接将接口返回的最外层数据赋值给状态后做单层map遍历,只能拿到内层的数组元素,无法直接访问到商品对象上的price、stock_count属性。

修复方法

两种实现方式,按需选择即可:

方案1:数据拉取阶段直接扁平化(推荐)

在拿到接口返回值后,用数组原生flat()方法把嵌套数组拍平成一维的商品对象数组,原有渲染逻辑不需要改动:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const API_URL = 'https://my-json-server.typicode.com/TomSearle/cb-devtest-api/products';

const MyComponent = () => {
  const [posts, setPosts] = useState([]);

  const fetchData = async () => {
    try {
      const { data } = await axios.get(API_URL);
      // 两层嵌套数组传参2做扁平化,确认层级固定也可以直接写data.flat()
      setPosts(data.flat(2));
    } catch (err) {
      console.error('商品数据拉取失败:', err);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
      {posts.length > 0 ? (
        <div>
          {posts.map((post) => (
            // 优先用post.id等商品唯一字段当key,临时测试可用索引
            <div key={post.id || post.price}>
              <h2>{post.price}</h2>
              <p>{post.stock_count}</p>
            </div>
          ))}
        </div>
      ) : (
        <p className="loading">Loading... </p>
      )}
    </div>
  );
};

export default MyComponent;

方案2:渲染阶段做双层遍历

如果不想修改拉取阶段的数据处理逻辑,可以在JSX渲染时做两层数组遍历,依次取出内层的商品对象:

return (
  <div>
    {posts.length > 0 ? (
      <div>
        {/* 第一层:遍历最外层数组 */}
        {posts.map((innerArr, outerIdx) => (
          <div key={outerIdx}>
            {/* 第二层:遍历内层数组拿到商品对象 */}
            {innerArr.map((post, innerIdx) => (
              <div key={post.id || innerIdx}>
                <h2>{post.price}</h2>
                <p>{post.stock_count}</p>
              </div>
            ))}
          </div>
        ))}
      </div>
    ) : (
      <p className="loading">Loading... </p>
    )}
  </div>
);
注意事项
  • React列表渲染必须给每一项设置唯一key属性,否则会抛出性能警告,优先使用接口返回的商品唯一ID作为key值,非必要不要用遍历索引
  • 建议给异步请求加try/catch错误捕获,避免接口异常时直接导致页面白屏
  • 如果不确定接口返回的数组嵌套深度,可以先在控制台打印完整返回值确认结构后,再调整flat()的入参

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 00:39:02