You need to enable JavaScript to run this app. React中useEffect+fetch获取API数据后map遍历渲染UI报错问题
优惠活动
大模型
产品
解决方案
定价
更多

React中useEffect+fetch获取API数据后map遍历渲染UI报错问题

错误原因

  1. map遍历的key属性赋值错误:遍历data.results数组时,单个遍历项是地震数据对象,不存在results属性,给key赋值undefined会触发React渲染异常。
  2. li标签未包裹在ul/ol列表容器内,不符合HTML规范,会触发DOM警告。
  3. 原代码对data.results的校验逻辑不严谨,未判断是否为数组类型,边界场景下容易报错。
  4. 请求回调逻辑有缺陷,若数据处理环节抛出异常会导致loading状态一直为true,无法结束加载。

修复后完整代码

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

export function App() {
  const [data, setData] = useState({
    results: []
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const api = "https://apis.is/earthquake/is";
  useEffect(() => {
    setLoading(true);
    fetch(api)
      .then((response) => response.json())
      .then((res) => {
        setData(res);
        setLoading(false);
      })
      .catch((err) => {
        setError(err);
        setLoading(false);
      });
  }, []);

  if (loading) return <h1>加载中...</h1>;
  if (error) return <pre>{JSON.stringify(error, null, 2)}</pre>;
  if (!data) return null;

  if (Array.isArray(data.results) && data.results.length) {
    return (
      <div>
        <ul>
          {data.results.map((item) => (
            <li key={item.timestamp}> {item.humanReadableLocation}</li>
          ))}
        </ul>
      </div>
    );
  }
  return <div>获取数据失败</div>;
}

修复说明

  • key优先使用数据自带的唯一标识timestamp,避免索引作为key带来的渲染性能问题和异常
  • 新增ul父容器包裹li标签,符合HTML语法要求
  • 优化data.results校验逻辑,增加数组类型判断,覆盖边界异常场景
  • 调整请求回调逻辑,将loading状态更新分别放到成功和失败分支,避免状态不同步的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:06:04