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

如何让React中的ViewButton调用JSON文件数据而非Constants表数据?

问题描述

我正在实现表格中ViewButton的功能,点击“View Inventory”按钮后需要展示JSON文件里的id、name等数据,但目前按钮点击后显示的是Constants表中的数据,不符合需求。

相关代码与截图

JSON文件示例

[
  {
    "id": "INV-001",
    "name": "办公笔记本",
    "quantity": 50
  },
  {
    "id": "INV-002",
    "name": "无线鼠标",
    "quantity": 30
  }
]

HomePage第155行的ViewButton代码

// 原代码(示例)
<ViewButton 
  onClick={() => openModal(Constants.defaultInventory)} 
  label="View Inventory" 
/>

截图说明

  • ViewButton外观:表格每行右侧的“View Inventory”按钮,样式为蓝色填充按钮
  • 当前错误效果:点击按钮后弹出的窗口展示了Constants表中预设的测试数据,而非JSON文件里的真实库存数据
解决方案

1. 正确导入/加载JSON数据

先确认你已经正确引入本地JSON文件:

// 替换为你的JSON文件实际路径
import inventoryData from './assets/data/inventory.json';

如果是从后端接口获取数据,需确保数据已成功拉取并存储到组件状态:

const [inventoryList, setInventoryList] = useState([]);

useEffect(() => {
  // 替换为你的实际接口地址
  fetch('/api/get-inventory')
    .then(res => res.json())
    .then(data => setInventoryList(data))
    .catch(err => console.error('加载库存数据失败:', err));
}, []);

2. 修改ViewButton的点击事件

把原代码中传入的Constants数据替换成JSON数据/状态数据:

// 修改后的ViewButton代码
<ViewButton 
  onClick={() => openModal(inventoryData)} // 用接口数据的话传inventoryList
  label="View Inventory" 
/>

3. 调整展示组件的数据渲染逻辑

负责展示数据的弹窗/页面组件,要确保它渲染的是传入的JSON数据,而非Constants中的内容:

const InventoryDetailModal = ({ data, onClose }) => {
  return (
    <div className="modal">
      <button onClick={onClose}>关闭</button>
      <div className="inventory-list">
        {data.map(item => (
          <div key={item.id} className="inventory-item">
            <p>ID: {item.id}</p>
            <p>名称: {item.name}</p>
            <p>库存数量: {item.quantity}</p>
          </div>
        ))}
      </div>
    </div>
  );
};

4. 常见问题排查

  • 核对JSON文件路径,避免因路径错误导致加载不到数据
  • 检查代码中是否有其他逻辑将Constants数据赋值给了展示变量
  • 类组件需确认state更新后,数据已正确传递到ViewButton的props中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:27:38