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

React中基于ECDC COVID-19 API处理日期数据的技术问询

React中处理ECDC COVID-19死亡病例数据的实现

1. 获取API数据并生成按日期汇总的死亡病例数组

在React组件中,我们可以通过fetch获取ECDC的COVID-19数据,将同一日期下所有国家的死亡病例求和后,生成目标数组。

核心处理逻辑:

  • 用临时对象按日期键存储累加的死亡数,高效合并同一日期的多国家数据
  • 将临时对象转换为数组,每个元素为包含date和totalDeaths的对象

示例代码:

import { useState, useEffect } from 'react';

function CovidDeathData() {
  const [dailyDeathData, setDailyDeathData] = useState([]);

  useEffect(() => {
    const fetchAndProcessData = async () => {
      try {
        const response = await fetch('https://opendata.ecdc.europa.eu/covid19/casedistribution/json/');
        const data = await response.json();
        
        // 临时对象:key为日期,value为累计死亡数
        const dateDeathMap = {};
        
        data.records.forEach(record => {
          const { dateRep, deaths } = record;
          const deathCount = parseInt(deaths, 10);
          
          dateDeathMap[dateRep] = (dateDeathMap[dateRep] || 0) + deathCount;
        });
        
        // 转换为目标数组
        const processedData = Object.entries(dateDeathMap).map(([date, totalDeaths]) => ({
          date,
          totalDeaths
        }));
        
        setDailyDeathData(processedData);
      } catch (error) {
        console.error('获取或处理数据失败:', error);
      }
    };

    fetchAndProcessData();
  }, []);

  return <div>数据加载中...</div>;
}

export default CovidDeathData;

注意:ECDC返回的日期格式为dd/mm/yyyy,处理时请保持格式统一,避免后续查询不匹配

2. 从数组中获取指定日期的数据

利用数组的find方法快速定位目标日期的数据,需保证传入的日期格式与数组中存储的格式一致(即dd/mm/yyyy)。

查询函数实现:

const getDeathsByDate = (targetDate) => {
  return dailyDeathData.find(item => item.date === targetDate);
};

// 使用示例:获取2023年1月1日的数据
const targetData = getDeathsByDate('01/01/2023');
// 找到数据则返回 { date: '01/01/2023', totalDeaths: xxx },否则返回undefined

如果需要支持其他日期格式(如yyyy-mm-dd),可先转换格式再匹配:

const formatDateToECDC = (dateString) => {
  const date = new Date(dateString);
  const day = String(date.getDate()).padStart(2, '0');
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const year = date.getFullYear();
  return `${day}/${month}/${year}`;
};

// 使用示例:将'2023-01-01'转换为ECDC格式
const formattedDate = formatDateToECDC('2023-01-01');
const targetData = getDeathsByDate(formattedDate);

完整组件示例

整合逻辑并添加查询交互:

import { useState, useEffect } from 'react';

function CovidDeathData() {
  const [dailyDeathData, setDailyDeathData] = useState([]);
  const [selectedDate, setSelectedDate] = useState('');
  const [result, setResult] = useState(null);

  useEffect(() => {
    const fetchAndProcessData = async () => {
      try {
        const response = await fetch('https://opendata.ecdc.europa.eu/covid19/casedistribution/json/');
        const data = await response.json();
        
        const dateDeathMap = {};
        data.records.forEach(record => {
          const deathCount = parseInt(record.deaths, 10);
          dateDeathMap[record.dateRep] = (dateDeathMap[record.dateRep] || 0) + deathCount;
        });
        
        const processedData = Object.entries(dateDeathMap).map(([date, totalDeaths]) => ({
          date,
          totalDeaths
        }));
        
        setDailyDeathData(processedData);
      } catch (error) {
        console.error('数据处理失败:', error);
      }
    };

    fetchAndProcessData();
  }, []);

  const handleSearch = () => {
    const data = dailyDeathData.find(item => item.date === selectedDate);
    setResult(data);
  };

  return (
    <div style={{ padding: '20px' }}>
      <h2>全球COVID-19每日死亡病例查询</h2>
      <div>
        <input
          type="text"
          placeholder="输入日期(格式:dd/mm/yyyy)"
          value={selectedDate}
          onChange={(e) => setSelectedDate(e.target.value)}
        />
        <button onClick={handleSearch}>查询</button>
      </div>
      {result ? (
        <p>日期 {result.date} 的全球累计死亡病例:{result.totalDeaths}</p>
      ) : selectedDate && (
        <p>未找到该日期的数据</p>
      )}
    </div>
  );
}

export default CovidDeathData;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:05:33