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

React useEffect获取新冠API数据渲染柱状图报错:TypeError: Cannot read property 'cases' of undefined

解决React中访问疫情数据时的Cannot read property 'cases' of undefined错误

嘿,我来帮你搞定这个问题!你碰到的TypeError: Cannot read property 'cases' of undefined错误主要来自这几个地方,咱们一步步拆解修复:

错误根源

  1. 初始数据为空:组件刚挂载时Dataa是个空数组,直接访问Dataa[val].cases时,Dataa[val]是undefined,自然没法读取cases属性。你虽然加了Dataa && ...,但这只判断了Dataa本身存在,没检查Dataa[val]是否有效。
  2. 索引越界风险:如果传入的val超出了接口返回数组的长度范围,Dataa[val]也会是undefined。
  3. 样式数组不匹配:你的backgroundColor只有3个颜色值,但data里有4个数据项,最后一个柱子会没有背景色。

修复方案

1. 添加加载状态

在数据未获取完成前,显示加载提示,避免渲染未准备好的图表。

2. 安全访问数据

用可选链操作符?.或者条件判断,确保Dataa[val]存在后再读取属性。

3. 处理索引边界

确保val是有效的数组索引,比如默认取0,或者当val超出范围时做兜底处理。

4. 匹配样式数组长度

让backgroundColor的元素数量和data一致。

修改后的完整代码

import React,{useState,useEffect} from 'react'
import {Bar} from 'react-chartjs-2';

const Chart = ({val}) => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(()=>{
    async function fetchData(){
      try {
        const apiResponse = await fetch('https://disease.sh/v3/covid-19/countries');
        const apiData = await apiResponse.json();
        setData(apiData);
      } catch (err) {
        console.error('数据获取失败:', err);
      } finally {
        setIsLoading(false);
      }
    }
    fetchData();
  },[])

  // 处理val的边界,确保索引有效
  const validIndex = val >=0 && val < data.length ? val : 0;
  // 安全获取当前国家的数据
  const currentCountryData = data[validIndex];

  const chartData = {
    labels: ['Total Cases', 'Deaths', 'Recovered','Active Cases'],
    datasets: [
      {
        label: currentCountryData ? currentCountryData.country : 'Loading...',
        backgroundColor: ['#737270','red','green','#1E90FF'], // 新增第四个颜色匹配active cases
        borderColor: 'rgba(255,99,132,1)',
        borderWidth: 1,
        hoverBackgroundColor: 'rgba(255,99,132,0.4)',
        hoverBorderColor: 'rgba(255,99,132,1)',
        data: [
          currentCountryData?.cases || 0,
          currentCountryData?.deaths || 0,
          currentCountryData?.recovered || 0,
          currentCountryData?.active || 0
        ]
      }
    ]
  }

  if (isLoading) {
    return <div>Loading data...</div>;
  }

  return (
    <div>
      <h2>{currentCountryData.country} 疫情数据</h2>
      <Bar data={chartData} width={100} height={190} options={{ maintainAspectRatio: false }} />
    </div>
  )
}

export default Chart;

关键修改点说明

  • 新增isLoading状态,在数据加载时显示提示,避免渲染错误。
  • 用validIndex处理val的边界问题,防止索引越界。
  • 使用可选链?.和默认值|| 0安全访问数据,即使currentCountryData是undefined也不会报错。
  • 补全backgroundColor的颜色值,确保每个数据项都有对应的背景色。
  • 把图表标题改成对应国家的名称,更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:26:16