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

React正确解析API返回JSON对象数组并渲染到UI的方案

问题定位

三个问题直接导致渲染失败:

  • React的状态更新是异步批处理的,setBeers(data)执行后立刻读beers拿到的永远是更新前的旧值,这是框架正常机制,不是解析出错。
  • 从你提供的返回数据结构截图可见,接口返回的是带外层包装的响应对象,真正的啤酒列表数组存在对象的子字段里(常见是data字段),你直接把整个响应对象赋值给beers,会让beers从初始的数组变成对象,后续调用map遍历会直接抛类型错误。
  • 渲染位置完全写错了:你把遍历逻辑塞到了表头的<th>标签里,本该放内容行的<tbody>代码全被注释,而且注释里写的userId/title是其他接口的字段,和啤酒数据的字段名根本对不上。
修复方案
  • 先从接口响应里取出真正的啤酒数组再赋值给状态,不要直接set整个响应对象
  • 把表格行的渲染逻辑移到<tbody>标签内,字段名和接口返回的实际字段保持一致
  • 加空状态兜底,避免无数据时页面结构错乱

修复后的完整代码:

import React, { useState } from "react";
import APIService from "./APIService";

export default function BeerComponent() {
  const [beers, setBeers] = useState([]);

  const handleFetchBeers = () => {
    APIService.getBeers()
      .then((response) => response.json())
      .then((res) => {
        // 这里如果你的接口数组字段不是data,打印res后替换成对应字段即可
        const beerList = res.data ?? [];
        setBeers(beerList);
        // 验证数据直接打印拿到的列表就行,不用在set后立刻读state
        console.log("接口返回的啤酒列表:", beerList);
      })
      .catch((err) => {
        console.log("请求失败,错误信息:", err);
      });
  }

  return (
    <div>
      <button onClick={handleFetchBeers}>Beer Button</button>
      <h2 className="text-center">Beer Details</h2>
      <table className="table table-striped">
        <thead>
          <tr>
            <th>Beer Id</th>
            <th>Beer Name</th>
            <th>Beer Company</th>
          </tr>
        </thead>
        <tbody>
          {
            beers.length ? 
            beers.map((beer) => (
              <tr key={beer.beerId || beer.id}>
                <td>{beer.beerId || beer.id}</td>
                <td>{beer.beerName}</td>
                <td>{beer.beerCompanyName}</td>
              </tr>
            )) :
            <tr>
              <td colSpan={3} className="text-center">点击按钮加载啤酒数据</td>
            </tr>
          }
        </tbody>
      </table>
    </div>
  );
}
调试提示
  • 如果取完res.data还是拿不到数组,直接在.then((res) => { console.log(res) })这里打完整响应,找到存数组的实际字段名替换就行,不同后端的接口包装字段可能是result/list/records这类。
  • 遍历列表的key一定要用每条数据的唯一标识(比如啤酒id),不要用数组下标,也不要用不存在的字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 02:09:10