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

如何在React中处理航班API的JSON数据,仅提取指定字段?

解决方案

首先,你的代码存在两个核心问题:一是直接用数组push修改数据不会触发React组件重渲染;二是没有正确处理API返回的以日期为键的嵌套数据结构。以下是修正后的完整方案:

1. 用useState管理状态

替换普通数组datos为React状态变量,确保数据更新时组件能重新渲染:

import { useEffect, useState } from 'react';

function FlightComponent() {
  // 初始化状态为空数组
  const [flightData, setFlightData] = useState([]);

  useEffect(() => {
    fetch(url, options)
      .then((res) => res.json())
      .then((json) => {
        // 处理API返回的数据
        const processedData = processFlightData(json);
        // 更新状态
        setFlightData(processedData);
      })
      .catch((err) => console.error('获取航班数据失败:', err));
  }, []);

  // 定义数据处理函数
  const processFlightData = (apiResponse) => {
    // 跳过success字段,提取所有日期对应的航班列表
    const dateFlightLists = Object.values(apiResponse).filter(item => Array.isArray(item));
    // 把多维数组扁平化,再提取需要的字段
    return dateFlightLists.flat().map(flight => ({
      origin: flight.origin,
      destination: flight.destination,
      price: flight.price
    }));
  };

  return (
    <div className='ejemplo'>
      {/* 渲染处理后的航班数据 */}
      {flightData.map((flight, index) => (
        <div key={index}>
          <p>出发地: {flight.origin}</p>
          <p>目的地: {flight.destination}</p>
          <p>价格: {flight.price}</p>
          <hr />
        </div>
      ))}
    </div>
  );
}

export default FlightComponent;

2. 关键逻辑说明

  • 状态管理:用setFlightData更新状态,替代原代码的datos.push,确保组件能感知数据变化并重新渲染。
  • 数据处理:
    1. 用Object.values(apiResponse)获取API返回对象的所有值,过滤出数组类型的航班列表(跳过success字段)。
    2. 用flat()把多个日期的航班数组合并成一维数组。
    3. 用map遍历每个航班对象,只提取origin、destination、price三个字段。
  • 渲染优化:不再直接输出JSON.stringify,而是把处理后的数据渲染成可读性更强的DOM结构。

3. 适配不同API结构的调整

如果API返回的日期键对应的是单个航班对象(而非数组),只需修改processFlightData函数:

const processFlightData = (apiResponse) => {
  // 跳过success字段,提取所有日期对应的航班对象
  const dateFlights = Object.values(apiResponse).filter(item => typeof item === 'object' && !Array.isArray(item));
  return dateFlights.map(flight => ({
    origin: flight.origin,
    destination: flight.destination,
    price: flight.price
  }));
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:55:19