【发布时间】:2018-01-18 03:39:56
【问题描述】:
我正在尝试显示我的 items 数组中的一个元素。我可以将元素记录到控制台...但无法渲染。在我的setState 中,我制作了 itemDetail,它从 items 数组中获取第一个元素:(也许有更好的方法来做到这一点?)
this.setState({ items: items, itemDetail: items[0], value: this.state.value })
当我尝试拨打 {itemDetail} 时,它给了我错误:
“对象作为 React 子对象无效(找到:带有键 {id, name} 的对象)....”
下面的完整代码。如何在 React 中渲染数组中的第一个元素?或者更好的是,按 ID 显示元素。谢谢。
constructor(props){
super(props);
this.state = {
items: []
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
componentDidMount(){
const items = [
{
'id': 0,
'name': 'firstName'
},
{
'id': 1,
'name': 'secondName'
}
];
this.setState({ items: items, itemDetail: items[0] });
}
render(){
const { items, itemDetail } = this.state;
console.log(itemDetail);
return(
<div className="container">
{itemDetail}
</div>
);
}
【问题讨论】:
标签: javascript arrays reactjs object element