我有一个对象数组。我想映射这个对象数组。我知道如何映射数组,但不知道如何映射对象数组。这是我到目前为止所做的:
我想要映射的对象数组:
const theData = [
{
name: 'Sam',
email: 'somewhere@gmail.com'
},
{
name: 'Ash',
email: 'something@gmail.com'
}
]
我的组件:
class ContactData extends Component {
render() {
//works for array
const renData = this.props.dataA.map((data, idx) => {
return <p key={idx}>{data}</p>
});
//doesn't work for array of objects
const renObjData = this.props.data.map(function(data, idx) {
return <p key={idx}>{data}</p>
});
return (
<div>
//works
{rennData}
<p>object</p>
//doesn't work
{renObjData}
</div>
)
}
}
ContactData.PropTypes = {
data: PropTypes.arrayOf(
PropTypes.obj
),
dataA: PropTypes.array
}
ContactData.defaultProps = {
data: theData,
dataA: dataArray
}
我错过了什么?
最佳答案
您需要的是映射对象数组并记住每个项目都是一个对象,以便您可以使用例如点表示法来获取对象的值。
在你的组件中
[
{
name: 'Sam',
email: 'somewhere@gmail.com'
},
{
name: 'Ash',
email: 'something@gmail.com'
}
].map((anObjectMapped, index) => {
return (
<p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
{anObjectMapped.name} - {anObjectMapped.email}
</p>
);
})
请记住,当您放置 jsx 数组时,它具有不同的含义,并且您不能像放置数组一样将对象放入渲染方法中。
看看我的回答 mapping an array to jsx
关于arrays - 如何在 React 中映射对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41027663/