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

React JS Hooks中API调用代码运行异常问题求助

问题根因

你的代码无法正常运行主要由以下问题导致:

  • customers状态初始值设为null,组件首次渲染时API请求尚未返回数据,直接执行customers.map()会触发类型错误:null 不存在 map 方法,直接中断组件渲染
  • 未对fetch请求做响应状态校验和错误捕获:fetch默认不会在接口返回4xx/5xx状态码时抛出错误,此时直接调用res.json()会解析失败;网络异常、跨域等场景下没有错误兜底也会导致代码崩溃
  • fetch语句末尾的**API CALLS**标记如果是直接写在代码里而非注释,会直接触发语法错误
修复方案

按以下步骤调整即可:

  • 将customers初始值改为空数组[],保证首次渲染时map方法可正常执行
  • 增加接口响应状态校验,只有请求成功时才解析返回的json数据
  • 增加catch错误捕获逻辑,同时可补充加载、错误状态的UI提示
  • 移除fetch行尾无意义的**API CALLS**标记,若需要写注释请使用//前缀

修复后的可运行代码:

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

function Customers() {
    const [customers, setCustomers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [errorMsg, setErrorMsg] = useState('');

    useEffect(() => {
        const getCustomerList = async () => {
            try {
                const res = await fetch('https://reactstarter-app.herokuapp.com/api/customers');
                if (!res.ok) throw new Error(`请求出错,状态码:${res.status}`);
                const list = await res.json();
                setCustomers(list);
            } catch (err) {
                setErrorMsg(err.message);
            } finally {
                setLoading(false);
            }
        };
        getCustomerList();
    }, []);

    if (loading) return <div>客户列表加载中...</div>;
    if (errorMsg) return <div>加载失败:{errorMsg}</div>;

    return (
        <div>
            <h2>Customers</h2>
            <ul>
                {customers.map((customer) => (
                    <li key={customer.id}>{customer.firstName} {customer.lastName}</li>
                ))}
            </ul>
        </div>
    );
}

export default Customers;

补充说明:如果运行时提示跨域错误,需要让后端接口配置对应CORS响应头,本地开发阶段也可以通过配置开发服务器代理的方式绕过跨域限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 12:30:48