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

React中渲染获取的数组数据?数组push及批量请求排序问题

问题分析与解决方案

一、console.log显示空数组的原因及修复

你的代码里push操作本身没有错误,出现空数组的显示问题主要有两个原因:

  1. 浏览器控制台的引用特性:浏览器控制台打印数组时,有时会显示数组的引用而非打印瞬间的快照。当你展开数组时才会读取最新值,但实际上在console.log执行时数组已经有内容了。可以通过打印数组拷贝来验证实际值:
.then(()=>console.log([...result]));
  1. React组件的变量作用域问题:如果这段代码写在React组件内部,let result = []是普通变量,组件重新渲染时会被重置。必须用React状态来管理数组,才能保证数据持久化:
import { useState, useEffect } from 'react';

function YourComponent() {
  const [result, setResult] = useState([]);

  useEffect(() => {
    fetch("http://你的目标URL")
      .then(res => res.json())
      .then(data => {
        setResult(prev => [...prev, data]); // 用状态更新函数获取最新状态
        console.log([...result, data]); // 直接打印新数组确认
      });
  }, []);

  return <div>{/* 组件渲染内容 */}</div>;
}

二、100次请求按顺序打印的实现

要实现按请求次数顺序打印,有两种常用方案:

方案1:串行请求(依次发起,完成一个再进行下一个)

适合要求请求严格按顺序发起的场景,缺点是总耗时较长:

const fetchSequentially = async () => {
  const result = [];
  for (let i = 1; i <= 100; i++) {
    try {
      const res = await fetch("http://你的目标URL");
      const data = await res.json();
      result.push(data);
      console.log(`count: ${i}`, data);
    } catch (err) {
      console.error(`第${i}次请求失败`, err);
    }
  }
  console.log("所有请求完成", result);
};

// 在React组件中调用
useEffect(() => {
  fetchSequentially();
}, []);

方案2:并行请求+按顺序输出

适合希望请求并发执行,但结果按序号顺序打印的场景,总耗时更短:

const fetchInParallel = async () => {
  // 预先创建100个请求的Promise,并带上序号
  const promises = Array.from({ length: 100 }, (_, index) => 
    fetch("http://你的目标URL")
      .then(res => res.json())
      .then(data => ({ count: index + 1, data }))
      .catch(err => ({ count: index + 1, error: err }))
  );

  // 等待所有请求完成后,按序号排序输出
  const results = await Promise.all(promises);
  results.sort((a, b) => a.count - b.count).forEach(item => {
    if (item.error) {
      console.error(`count: ${item.count} 请求失败`, item.error);
    } else {
      console.log(`count: ${item.count}`, item.data);
    }
  });
};

// 在React组件中调用
useEffect(() => {
  fetchInParallel();
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 02:33:25