如何在 React 中正确处理并提取 JSON API 响应中的特定字段

11次阅读

如何在 React 中正确处理并提取 JSON API 响应中的特定字段

本文详解 react 中安全获取、解析和渲染 json 数据的最佳实践,包括状态管理、数据结构转换、条件渲染及常见错误规避。

react 应用中处理来自 rest apijsON 数据时,仅调用 res.json() 并直接 console.log 是远远不够的——真正关键的是结构化地提取、安全地存储、健壮地渲染所需字段(如 origin、destination、price)。你提供的原始代码存在多个典型问题:使用普通数组 datos.push() 而非 useState 状态更新、未解构嵌套数据、缺少加载/错误状态、且直接 json.stringify(datos) 无法实现语义化展示。

以下是推荐的完整解决方案(含关键改进说明):

✅ 正确做法:使用 useState + 解构 + 映射渲染

import { useState, useEffect } from 'react'; function FlightList() { const [datos, setDatos] = useState([]); // ✅ 使用 useState 管理响应数据 const [loading, setLoading] = useState(true); // ✅ 添加加载状态 const [error, setError] = useState(null); // ✅ 添加错误状态 useEffect(() => { const fetchData = async () => { try { setLoading(true); const response = await fetch(url, options); if (!response.ok) throw new Error(`HTTP ${response.status}`); const json = await response.json(); // ✅ 安全解构:检查 success 和 data 是否存在 if (!json.success || !json.data) { throw new Error('Invalid API response: missing success flag or data'); } // ✅ 提取目标字段:遍历 data 对象的每个日期键,构造精简数组 const dataList = Object.entries(json.data).map(([date, flight]) => ({ date, // 可选:保留日期作为上下文 origin: flight.origin, destination: flight.destination, price: flight.price, })); setDatos(dataList); } catch (err) { console.error('Fetch error:', err); setError(err.message); } finally { setLoading(false); } }; fetchData(); }, []); // ✅ 条件渲染:避免空数据或 loading 时渲染无效内容 if (loading) return 

Loading flights...

; if (error) return

Error: {error}

; return (

{datos.length === 0 ? (

No flights available.

如何在 React 中正确处理并提取 JSON API 响应中的特定字段

聚蜂消防BeesFPD

关注消防领域的智慧云平台

下载

) : ( datos.map((flight, index) => (

{flight.origin} → {flight.destination}

Price: €{flight.price}

Date: {flight.date}

)) )}

text=ZqhQzanResources