【发布时间】:2021-11-21 11:42:57
【问题描述】:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
{const CustomerList = () => {
const [information, setInformation] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
if (isLoading) {
axios.get('').then((response) => {
setInformation((prevInfo) => {
return [...prevInfo, response.data];
});
});
}
return () => {
setIsLoading(false);
};
}, [information, isLoading]);
return (
<>
<h2>Name: </h2>
{information.map((item, index) => (
<div>
<div>{item[index].customer.firstName}</div>
<div>{item[index].customer.lastName}</div>
</div>
))}
</>
);
};
export default CustomerList;
- 我正在使用 axios 和 useEffect 从 api 获取数据
- 我通过数据的响应数组进行映射,如果数组中没有信息,则应用程序中断
- 如何仅映射数组中特定数量的项目?
- 例如,如果我的数据数组中有 3 个项目,它将在浏览器上从返回语句向下显示 但是...当它映射所有 3 个时,它将继续重试并中断,因此“客户未定义”,因为没有更多客户 5.我尝试做 {item.customer.firstName 并得到 undefined first name 的错误}
有什么办法可以解决这个问题?谢谢!
【问题讨论】:
标签: javascript arrays reactjs api array.prototype.map