
本文详解如何在 react 中正确获取、解析嵌套 json 数据(如对象形式的产品列表),转换为数组后按 popularity 字段降序排序,并安全渲染,避免因数据结构误判导致的“无法显示数据”问题。
本文详解如何在 react 中正确获取、解析嵌套 json 数据(如对象形式的产品列表),转换为数组后按 popularity 字段降序排序,并安全渲染,避免因数据结构误判导致的“无法显示数据”问题。
在使用 fetch 请求类似 这类 API 时,一个常见误区是错误预设响应数据结构。该接口返回的并非扁平数组,而是一个包含 products 键的对象,其值为以 ID 为键、产品信息为值的映射对象(即 { "1": {title: "...", price: ..., popularity: ...}, "2": {...} })。若直接调用 Object.values(print) 或误用 print.data,将导致 undefined 或空数组,最终 products.map() 报错或静默失败——这正是 “Cant display data” 的根本原因。
✅ 正确解析与排序流程
-
确认 API 响应结构:先
console.log(print)查看实际返回内容,确认数据位于print.products; -
将对象转为数组:使用
Object.entries()获取[key, value]对,再通过.map()构建带id的标准数组项; -
安全排序:对生成的数组按
product.popularity(注意小写)降序排列; -
统一字段命名:API 中字段为小写(
title,price,popularity),JSX 中需严格匹配,避免product.Title或product.Popularity等大小写错误。
以下是修正后的完整可运行代码:
import { useState, useEffect } from 'react';
export const App = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(
'https://s3.amazonaws.com/open-to-cors/assignment.json'
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// ✅ 关键修正:正确提取 products 对象并转为数组
const productArray = Object.entries(data.products).map(([id, product]) => ({
id,
...product // 展开保留 title, price, popularity 等字段
}));
// ✅ 按 popularity 降序排序(注意小写)
const sortedProducts = [...productArray].sort(
(a, b) => b.popularity - a.popularity
);
setProducts(sortedProducts);
} catch (error) {
console.error('Failed to fetch or process products:', error);
// 可选:设置 error state 并在 UI 提示用户
}
};
fetchData();
}, []);
return (
<div>
<h1>Product List</h1>
{products.length === 0 ? (
<p>Loading products or no data available...</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill11824" title="shopify-app-react-router"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20dee630206.jpg" alt="shopify-app-react-router" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill11824" title="shopify-app-react-router" class="overflowclass">shopify-app-react-router</a>
<p class="overflowclass">构建 Shopify 嵌入式应用(Embedded App)的开发技能:基于 @shopify/shopify-app-react-router + React Router v7 + Admin API 2026-04。覆盖 shopifyApp 配置、authenticate.admin 的 GraphQL/REST 调用、Webhook 校验、Session 存储、订阅计费、App Bridge 导航、部署,并新增:适用场景判断、安全最佳实践、错误处理与容错、最佳实践、常见问题 FAQ、高级场景。G</p>
</div>
<a rel="nofollow" href="/xiazai/skill11824" title="shopify-app-react-router" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
) : (
<ul>
{products.map((product) => (
<li key="{product.id}"> {/* ✅ 推荐使用 product.id 而非 index */}
<strong>Title:</strong> {product.title},
<strong>Price:</strong> ${product.price},
<strong>Popularity:</strong> {product.popularity}
</li>
))}
</ul>
)}
</div>
);
};
export default App;
⚠️ 注意事项与最佳实践
-
不要直接修改原数组:
sort()是原地操作,建议用[...productArray].sort(...)创建副本,避免副作用; -
key 值必须稳定唯一:使用
product.id(来自 API)比index更可靠,防止列表更新时渲染异常; -
添加加载与错误状态:生产环境应加入
loading和errorstate,提升用户体验; -
字段名严格区分大小写:该 API 使用全小写字段(
price,popularity),React 组件中必须完全一致; -
验证响应状态:增加
if (!response.ok)判断,避免静默失败。
通过以上步骤,即可彻底解决“数据无法显示”问题,并构建出健壮、可维护的数据获取与展示逻辑。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










