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

React中使用.map处理图表API数据时出现未定义读取错误

解决React中.map处理API数据时的"Cannot read properties of undefined (reading 'map')"错误

我想把API返回的数据展示在图表上,已知实现逻辑,但使用.map函数时出现错误。需要拆分prices数组里每个子数组的第0项和第1项,分别作为图表的x、y值。

API返回的数据格式

"prices": [
    [
      1689598842536,
      30208.47
    ],
    [
      1689602431443,
      30274.72
    ]
]

我的代码

const params = useParams()
const [coin, setCoin] = useState({})
const [chart, setChart] = useState({})
const [loading, setLoading] = useState(false)

const chartUrl = `https://api.coingecko.com/api/v3/coins/${params.coinId}/market_chart?vs_currency=usd&days=30&precision=2`

const url = `https://api.coingecko.com/api/v3/coins/${params.coinId}`

useEffect(() => {
    axios.get(url).then((res) => {
        setCoin(res.data)
        setLoading(true)
    }).catch((error) => {
        console.log(error)
    })

    axios.get(chartUrl).then((res) => {
        setChart(res)
    }).catch((error) => {
        console.log(error)
    })
}, [])

const coinChartData = chart.prices.map(value => ({x: value[0], y: value[1]}))

出现的错误

Cannot read properties of undefined (reading 'map')

尝试过的操作

我试过把coinChartData的定义放到useEffect里,代码能正常运行,但没办法在useEffect外部使用这个变量。


问题根源

  1. 组件初次渲染时,chart的初始值是空对象,chart.prices为undefined,调用map自然会报错。
  2. 另外,axios请求返回的res是完整响应对象,实际接口数据存在res.data里,你现在把整个res存到chart状态中,就算请求完成后,chart.prices也无法正确获取到数据。

解决方案

方案一:可选链+默认数组

直接在map前加可选链判断,同时给个默认空数组,避免初次渲染报错:

const coinChartData = chart.prices?.map(value => ({x: value[0], y: value[1]})) || []

方案二:修正状态初始化与数据存储

  • 把chart的初始状态设为包含空prices数组的对象,确保初次渲染时chart.prices是数组:
const [chart, setChart] = useState({ prices: [] })
  • 存数据时要存res.data而非整个响应对象:
axios.get(chartUrl).then((res) => {
    setChart(res.data) // 这里改为res.data
}).catch((error) => {
    console.log(error)
})

方案三:条件渲染控制

在渲染图表时,先判断chart.prices是否存在且有数据,再进行渲染:

return (
    <div>
        {chart.prices?.length > 0 ? (
            {/* 这里渲染你的图表组件,传入coinChartData */}
        ) : (
            <p>加载中...</p>
        )}
    </div>
)

内容的提问来源于stack exchange,提问作者Jakub Polański

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:57:35