React中如何访问嵌套对象?Axios获取的嵌套对象无法在页面渲染
解决React渲染嵌套接口数据的方案
你的现有代码存在两个核心问题:1、return 节点内没有编写任何渲染逻辑;2、异步请求完成前axieStats是空对象,直接访问内部属性会抛出运行时错误。
以下是可直接运行的修改后代码:
import React, { useState, useEffect } from "react" import Axios from "axios" const Axie = () => { const [axieStats, setAxieStats] = useState({}) const [loading, setLoading] = useState(true) const [error, setError] = useState('') const fetchAxie = async () => { try { setLoading(true) const response = await Axios( "https://game-api.axie.technology/api/v1/ronin:0d771f9d749fe72671526e0a52ecdfc11f73ca7b,ronin:b9603b5ae4d10fce072432d99de572c1eb66b43e" ) setAxieStats(response.data) setError('') } catch (err) { setError('数据拉取失败,请稍后重试') } finally { setLoading(false) } } useEffect(() => { fetchAxie() }, []) // 请求过程中展示加载态 if (loading) return <div>数据加载中...</div> // 请求失败展示报错信息 if (error) return <div>{error}</div> // 将外层嵌套对象转为数组,方便遍历渲染 const statList = Object.values(axieStats) return ( <div> <h2>Axie 数据列表</h2> {statList.map((item, index) => ( <div key={index} style={{border: '1px solid #eee', padding: '10px', margin: '10px 0'}}> <p>名称:{item?.name}</p> <p>MMR:{item?.mmr}</p> <p>状态:{item?.success ? '正常' : '异常'}</p> <p>下次领取时间:{new Date(item?.next_claim * 1000).toLocaleString()}</p> </div> ))} </div> ) } export default Axie
关键逻辑说明
- 新增
loading和error状态处理请求边界情况,避免页面空白或者报错崩溃 - 用
Object.values(axieStats)把外层的键值对对象转为数组,可直接用map方法遍历渲染所有子项,不需要手动写test1、test2等固定key - 访问子属性时用可选链运算符
?.做兜底,就算某条数据缺少对应字段也不会报错 - 示例中把时间戳转成了可读的本地时间格式,你可以根据需求调整展示逻辑
如果需要单独访问某条固定数据,可直接用属性访问的方式:
// 直接访问test1的数据 <div> <p>test1的名称:{axieStats?.test1?.name}</p> <p>test1的MMR:{axieStats?.test1?.mmr}</p> </div>
内容的提问来源于stack exchange,提问作者Pinky Promise
相关产品推荐
相关产品推荐

