[英]why can't i acces elements in an array of JSONs
I'm trying to map through an Array of Objects, every object is fetched from a folder of JSONs in my project.我正在尝试通过对象数组进行映射,每个对象都是从我项目中的 JSON 文件夹中获取的。 then i want to Render each object as a react component.然后我想将每个对象渲染为一个反应组件。 to achieve this i set the state of my component to that array of object.为此,我将组件的状态设置为该对象数组。
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
when i console.log() my state it seems to be what i needed, but when i try to console.log() the first element of that array it is undefined.当我使用 console.log() 我的状态时,它似乎是我所需要的,但是当我尝试使用 console.log() 时,该数组的第一个元素是未定义的。 this is the console.log(this.state.data)这是 console.log(this.state.data)
[]
0: {description: "AirEuropa Boarding Pass", organizationName: "Air Europa", passTypeIdentifier: "pass.com.globalia.aireuropa.boardingpass", serialNumber: "RB47ZP20082C640001010191641560895200000", teamIdentifier: "ELASV6M68G", …}
1: {formatVersion: 1, passTypeIdentifier: "pass.com.renfe-RenfeTicket", serialNumber: "00HHGV7F7353900982276", teamIdentifier: "H9VY2F2XZA", webServiceURL: "https://www.myserver.com/pathto/service", …}
length: 2
__proto__: Array(0)
why is this.state.data[0] undefined?为什么 this.state.data[0] 未定义?
This is how i get data from JSONs这就是我从 JSON 获取数据的方式
const arr = [];
axios
.get("data")
.then(res => {
const arrayDatas = res.data;
arrayDatas.forEach(element => {
if (element.includes(".json")) {
axios.get("data/" + element).then(res => {
arr.push(res.data);
});
}
});
this.setState({
data: arr
});
})
.catch(error => console.error(error));
}
You should update your state as suggested below.您应该按照下面的建议更新您的状态。
const arr = [];
axios
.get("data")
.then(res => {
const arrayDatas = res.data;
arrayDatas.forEach(element => {
if (element.includes(".json")) {
axios.get("data/" + element).then(res => {
arr.push(res.data);
});
}
});
this.setState({
data: arr
});
})
.catch(error => console.error(error));
}
const arr = [];
axios
.get("data")
.then(res => {
const arrayDatas = res.data;
arrayDatas.forEach(element => {
if (element.includes(".json")) {
axios.get("data/" + element).then(res => {
this.setState({data: res.data});
});
}
})
.catch(error => console.error(error));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.