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

React组件中如何从public目录JSON文件提取并展示客户名称

问题原因
  • 你存储状态时错误地将整个JSON对象包裹进了新数组,setCustomers([data])执行后,你的customers状态结构为 [{customers: [客户列表], packages: [包裹列表]}],不是预期的客户数组,这也是你尝试用customers.customers或customers["customers"]取不到值的原因,因为此时customers是数组,不是对象。
  • 你没有从返回的JSON数据中提取customers字段就直接存储,无法直接遍历拿到客户名称属性
修正后完整代码
import React from 'react';
export default function Customers (props) {
   const [customers, setCustomers] = React.useState([]);
   React.useEffect(() => { 
      fetch("/data.json").then(response => response.json())
      .then(data => {
         // 直接取JSON中的customers数组存入状态,不需要额外包裹数组
         setCustomers(data.customers)
      })
   }, []);

   return (
      <div id='Customers'>
         {/* 遍历列表建议加唯一key属性,避免React抛出警告 */}
         {customers.map(c => <span key={c.id}>{c.name}</span>)}
      </div>
   )
}
可选优化方案

如果你需要同时存储JSON中所有数据(包含packages字段),可以调整状态结构为对象,示例如下:

import React from 'react';
export default function Customers (props) {
   // 初始状态改为对象,包含customers和packages两个数组字段
   const [sourceData, setSourceData] = React.useState({customers: [], packages: []});
   React.useEffect(() => { 
      fetch("/data.json").then(response => response.json())
      .then(data => {
         setSourceData(data)
      })
   }, []);

   return (
      <div id='Customers'>
         {sourceData.customers.map(c => <span key={c.id}>{c.name}</span>)}
      </div>
   )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:45:03