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

React中使用useState Hook如何从JSON数据提取并设置价格数组状态

核心修改方案

你不需要使用forEach或者for循环,使用JavaScript数组内置的map方法即可快速提取所有price字段值,修改对应useEffect代码如下:

useEffect(() => {
    fetch(`/data/detailPageData.json`)
      .then(res => res.json())
      .then(data => {
        // map遍历order_history每一项,只返回price字段,组成新的价格数组
        const priceList = data.result.order_history.map(item => item.price)
        setMarketPriceData(priceList)
      });
  }, []);

同时注意你声明state的代码多写了一个const,修正为:

const [marketPriceData, setMarketPriceData] = useState([]);

额外优化建议

你当前代码里存在两次重复请求/data/detailPageData.json的逻辑,可以合并为同一个useEffect,减少不必要的网络请求:

// 删掉原来两个分别请求的useEffect,替换为下方代码即可
useEffect(() => {
    fetch(`/data/detailPageData.json`)
      .then(res => res.json())
      .then(data => {
        const result = data.result
        setDetailPageData(result)
        // 同时提取价格数组赋值
        setMarketPriceData(result.order_history.map(item => item.price))
      });
}, []);

修改完成后marketPriceData就会是你需要的纯价格值组成的数组,可以直接供给图表组件使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:45:09