我正在开发一个 react.js
项目,我需要访问一组对象。我从外部 URL
获取对象,那里没有问题。在我的 component
的 render
方法中,我可以看到数组:
const array = this.state.data.myArray;
console.log({array});
现在我尝试查看第一个对象:
console.log({array}[0]);
但它是未定义
。
我尝试了带或不带大括号的各种组合,但它总是未定义,或者给出意外标记
错误。
如何获取数组的对象?
编辑:
看起来我的 render
方法被调用了两次。第一次是数组undefined
,第二次是有数据,但现在它不再渲染。
这是我的组件:
import React from 'react'
class Hello extends React.Component {
constructor() {
super();
this.state = { data: [] };
}
async componentDidMount() {
const url = 'http://localhost:9000/SomeJson/id';
const response = await fetch(url);
const data = await response.json();
this.setState({ data });
console.log(data); // data shows up in the console
}
render() {
alert(this.state.data.theArray);
return(
<div><h2>hello</h2></div>
);
}
}
export default Hello;
我在这里缺少什么?
最佳答案
const { myArray = [] } = this.state.data || {}
您应该检查 data key 是否是一个有效的对象,然后对 myArray 进行解构,如果 myArray 未定义,则用空数组初始化它。
关于javascript - 在 React.js 中通过索引访问对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59952104/