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

React渲染NASA嵌套API报Objects are not valid as a React child错误

问题原因

你触发的Objects are not valid as a React child报错,本质是三个代码问题:

  • 直接将JS对象(你定义的results变量)插入JSX渲染,React仅支持渲染字符串、数字、合法JSX节点等基础类型,不支持直接渲染原生对象
  • 仅遍历了NASA返回数据的第一层,没有拆解near_earth_objects下按日期分组的嵌套结构,拿到的多层嵌套对象直接渲染必然报错
  • 代码存在逻辑疏漏:nasa的初始值设为空数组,但接口实际返回对象类型;代码中调用了setIsError但未定义对应state,会额外触发运行时错误。
正确实现方案

首先理清NASA近地天体接口的返回层级,逐层拆解后再渲染:

  1. 第一层根对象包含element_count(天体总数)、links(分页链接)、near_earth_objects(核心天体数据)三个字段
  2. near_earth_objects为对象结构,key是日期字符串(如2015-09-08),value是对应日期的近地天体数组
  3. 每个天体对象包含星等、直径、id、接近数据等属性,其中close_approach_data也是数组结构,需要二次拆解

修正后可运行代码

import styles from '../styles/Home.module.css'
const axios = require('axios')
import { useState } from 'react'

export default function Home() {
    // 接口返回对象类型,初始值设为null更合理,不要用空数组
    const [nasa, setNasa] = useState(null)
    const [posts, setPosts] = useState([])
    // 补全缺失的错误状态
    const [isError, setIsError] = useState(false)

    const returnNestedObjects = () => {
        setIsError(false)
        axios
            .get(
                'https://api.nasa.gov/neo/rest/v1/feed?start_date=2015-09-07&end_date=2015-09-08&api_key=hqIAqlEjXdGOE4K0H44Oj0Bq20tID1ytS3IdYuT4'
            )
            .then((response) => {
                setNasa(response.data)
            })
            .catch((error) => {
                setIsError(true)
                console.log(error)
            })
    }

    const getArrayofObjects = () => {
        setIsError(false)
        axios
            .get('https://jsonplaceholder.typicode.com/posts')
            .then((response) => {
                setPosts(response.data)
            })
            .catch((error) => {
                setIsError(true)
                console.log(error)
            })
    }

    return (
        <div className={styles.container}>
            <main className={styles.main}>
                <h1 className={styles.title}>
                    Welcome to{' '}
                    <span className={styles.headerTitle}>
                        <h2>Testing API API</h2>
                    </span>
                </h1>
                {isError && <p className={styles.error}>接口请求失败,请稍后重试</p>}
                <div className={styles.buttoncontainer}>
                    <button onClick={returnNestedObjects}>Nested Objects</button>
                    <button onClick={getArrayofObjects}>Array of Objects</button>
                </div>
                {/* 数组类型接口原有渲染逻辑正常,补充key属性即可 */}
                <section>
                    <h3>JSONPlaceholder 文章列表</h3>
                    <ul>
                        {posts.map((item) => (
                            <li key={item.id}>{item.title}</li>
                        ))}
                    </ul>
                </section>
                {/* NASA嵌套数据逐层拆解渲染 */}
                <section>
                    <h3>NASA 近地天体数据</h3>
                    {!nasa ? (
                        <p>点击上方按钮加载NASA数据</p>
                    ) : (
                        <div>
                            <p>近地天体总数:{nasa.element_count}</p>
                            {/* 遍历日期分组 */}
                            {Object.keys(nasa.near_earth_objects).map(dateKey => {
                                const neoList = nasa.near_earth_objects[dateKey]
                                return (
                                    <div key={dateKey} className={styles.dateGroup}>
                                        <h4>日期:{dateKey}</h4>
                                        <ul>
                                            {/* 遍历当天的所有天体 */}
                                            {neoList.map(neo => (
                                                <li key={neo.id} className={styles.neoItem}>
                                                    <p>天体ID:{neo.id}</p>
                                                    <p>绝对星等:{neo.absolute_magnitude_h}</p>
                                                    <p>
                                                        接近地球时间:
                                                        {neo.close_approach_data[0]?.close_approach_date || '无数据'}
                                                    </p>
                                                </li>
                                            ))}
                                        </ul>
                                    </div>
                                )
                            })}
                        </div>
                    )}
                </section>
            </main>
        </div>
    )
}
开发注意事项
  • 所有插入JSX渲染的值必须是基础类型(字符串、数字),如果需要展示完整对象结构,必须用JSON.stringify(目标对象)转成字符串,不能直接放置原生对象
  • 遍历列表时必须给节点加唯一key属性,否则React会抛出渲染警告
  • 嵌套结构要按层级拆解:对象类型用Object.keys/Object.entries/Object.values转成可遍历列表,拿到数组后再用map渲染单项
  • state初始值要和接口返回类型匹配:返回对象初始值用null,返回数组初始值用[],避免类型不匹配导致的逻辑错误
  • 访问深层嵌套属性时建议用可选链?.,避免某层数据缺失时抛出Cannot read properties of undefined错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 11:54:21