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

React中如何从含多层数组的JSON API获取数据?

问题描述

我尝试使用map()方法从NASA的DONKI/CME API获取数据,接口地址:https://api.nasa.gov/DONKI/CME?startDate=yyyy-MM-dd&endDate=yyyy-MM-dd&api_key=DEMO_KEY。目前能成功读取主数组内容,但遍历主数组内部嵌套数组时出现React错误,需要获取的内容已在图片中高亮(注:原问题提及图片但未提供)。

我的实现代码

React组件代码

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


const AstronomyPic = () => {
    const [images, setImages] = useState([])

    useEffect(() => {
        axios.get('https://api.nasa.gov/DONKI/CME?startDate=yyyy-MM-dd&endDate=yyyy-MM-dd&api_key=DEMO_KEY')
          .then(response => setImages (response.data)).
    catch(error =>console.error(" Error fetchin users", error)); 
      }, []);
  return (
    <div>

        <h1 className="text-center mt-5">Astronomy</h1>
        <ol>
        {images.map((image) => (
        <div><li>
          <p>{image.activityID}</p>
          <p>{image.catalog}</p>
          <p>{image.startTime}</p>
          <p>{image.sourceLocation}</p>
          <p>{image.activeRegionNum}</p>
          <p>{image.link}</p>
          <p>{image.note}</p>
          <p>Items: {images.items.map((item) => (
            <p>{item.instruments}</p>
          ))}</p>
          </li>
         
        </div>
         
      ))}
      </ol>
      

</div>

)

}

export default AstronomyPic

HTML依赖脚本

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
修复方案

核心错误修正

你代码里的关键问题是遍历嵌套数组时,错误调用了全局的images.items,而应该使用当前遍历项image的items属性。另外要处理image.items可能为空或不存在的情况,避免React抛出Cannot read properties of undefined错误。

修改后的列表渲染部分:

{images.map((image, index) => (
  <div key={index}>
    <li>
      <p>{image.activityID}</p>
      <p>{image.catalog}</p>
      <p>{image.startTime}</p>
      <p>{image.sourceLocation}</p>
      <p>{image.activeRegionNum}</p>
      <p>{image.link}</p>
      <p>{image.note}</p>
      <p>Items: 
        {/* 使用可选链操作符?.避免空值报错,同时添加key属性 */}
        {image.items?.map((item, itemIndex) => (
          <p key={itemIndex}>{item.instruments}</p>
        ))}
      </p>
    </li>
  </div>
))}

其他细节优化

  1. 添加key属性:React列表渲染要求每个子元素必须有唯一的key属性,帮助React高效更新DOM。
  2. 修正语法错误:原useEffect中的catch语句缩进和拼写有误,修正后更规范:
useEffect(() => {
  axios.get('https://api.nasa.gov/DONKI/CME?startDate=2023-01-01&endDate=2023-01-31&api_key=DEMO_KEY')
    .then(response => setImages(response.data))
    .catch(error => console.error("Error fetching data", error)); 
}, []);
  1. 替换日期参数:记得把URL中的yyyy-MM-dd替换为实际的日期范围,比如2023-01-01和2023-01-31,否则API可能返回空数据集。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 12:33:24