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

React应用无法获取展示并按热度排序数据问题求助

问题解决:React获取API数据并按热度排序失效

错误原因分析

你的代码里有几个关键问题导致排序和渲染失效:

  • 数据结构解析错误:目标API返回的是一个包含products字段的对象,你用Object.values(print)把整个对象转成数组后,又错误地去访问ans.data(该字段不存在),正确做法是直接提取print.products数组。
  • 排序结果未正确赋值:你已经生成了排序后的sortedProducts,但最后setProducts传入的是ans(错误的数组),等于白做了排序操作。
  • 原地排序的副作用:Array.sort()会直接修改原数组,建议先复制数组再排序,避免意外修改原始数据引发的潜在问题。

修正后的完整代码

import React, { useState, useEffect } from "react";

const App = () => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(
          "https://s3.amazonaws.com/open-to-cors/assignment.json"
        );
        const data = await response.json();
        // 提取正确的产品数组,先复制再按热度降序排序
        const sortedProducts = [...data.products].sort(
          (a, b) => b.Popularity - a.Popularity
        );
        setProducts(sortedProducts);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>Product List</h1>
      <ul>
        {products.map((product, index) => (
          <li key={index}>
            <strong>Title:</strong> {product.title}, 
            <strong>Price:</strong> {product.Price}, 
            <strong>Popularity:</strong> {product.Popularity}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default App;

关键修正点说明

  1. 正确解析API响应:直接使用data.products获取产品数组,这是API返回的正确数据结构。
  2. 安全排序:用扩展运算符[...data.products]复制原数组,再对副本排序,避免修改原始数据。
  3. 传递正确的排序结果:将排序后的sortedProducts传入setProducts,确保状态里存储的是已经排好序的数据。

内容的提问来源于stack exchange,提问作者Nishant Taliwal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:41:09