React用useEffect调API报undefined但componentDidMount正常是什么原因?
问题根因
这个差异和useEffect、componentDidMount的执行逻辑无关,完全是两段代码的状态取值逻辑不一致导致的:
- 函数组件中你给
customers的初始值是空数组[],接口请求是异步操作,首次渲染时接口还没返回结果,此时模板直接执行customers.data.map——数组本身没有data属性,customers.data为undefined,调用map方法自然就抛出了Cannot read property of undefined错误。 - 类组件的写法里,你将接口返回的
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
相关产品推荐
相关产品推荐

