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

React用useEffect调API报undefined但componentDidMount正常是什么原因?

问题根因

这个差异和useEffect、componentDidMount的执行逻辑无关,完全是两段代码的状态取值逻辑不一致导致的:

  1. 函数组件中你给customers的初始值是空数组[],接口请求是异步操作,首次渲染时接口还没返回结果,此时模板直接执行customers.data.map——数组本身没有data属性,customers.data为undefined,调用map方法自然就抛出了Cannot read property of undefined错误。
  2. 类组件的写法里,你将接口返回的res.data直接赋值给state.customers,初始值也是空数组,模板直接调用this.state.customers.map,空数组调用map方法不会报错,只是不会渲染任何内容,等接口返回更新状态后就能正常渲染。

修复方案

直接修改函数组件模板里的遍历逻辑即可,你调用setCustomers(data)时已经把接口返回的列表存在customers状态里,不需要额外加.data:

// 把原来的customers.data.map改成下面的写法
{customers.map((customer) => (
  <tr>
    <th scope="row">{customer.account_no}</th>
    <td>{customer.name}</td>
    <td>{customer.email}</td>
    <td>{customer.balance}</td>
  </tr>
))}

如果想要更稳妥避免类似报错,可以加上可选链判断:

{customers?.map((customer) => (...))}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 21:36:03