问题描述
我有一个对象数组.我想映射这个对象数组.我知道如何映射数组,但不知道如何映射对象数组.这是我到目前为止所做的:
我要映射的对象数组:
const theData = [{名称:山姆",电子邮件:'[email protected]'},{名称:'灰',电子邮件:'[email protected]'}]
我的组件:
class ContactData 扩展组件 {使成为() {//适用于数组const renData = this.props.dataA.map((data, idx) => {返回 <p key={idx}>{数据}</p>});//不适用于对象数组const renObjData = this.props.data.map(function(data, idx) {返回 <p key={idx}>{数据}</p>});返回 (//作品{rennData}<p>对象</p>//不起作用{renObjData}</div>)}}ContactData.PropTypes = {数据:PropTypes.arrayOf(道具类型.obj),数据A:PropTypes.array}ContactData.defaultProps = {数据:数据,数据A:数据数组}我错过了什么?
解决方案 你需要映射你的对象数组并记住每个项目都是一个对象,这样你就可以使用例如点符号来获取值对象.
在你的组件中
[{名称:山姆",电子邮件:'[email protected]'},{名称:'灰',电子邮件:'[email protected]'}].map((anObjectMapped, index) => {返回 (<p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>{anObjectMapped.name} - {anObjectMapped.email}</p>);})
请记住,当您放置一个 jsx 数组时,它具有不同的含义,您不能只将对象放入您的渲染方法中,因为您可以放置一个数组.
看看我在 将数组映射到jsx
I have an array of objects. I would like to map this array of objects. I know how to map an array, but can't figure out how to map an array of objects. Here is what I have done so far :
The array of objects I want to map :
const theData = [
{
name: 'Sam',
email: '[email protected]'
},
{
name: 'Ash',
email: '[email protected]'
}
]
My component :
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
}
What am I missing ?
解决方案 What you need is to map your array of objects and remember that every item will be an object, so that you will use for instance dot notation to take the values of the object.
In your component
[
{
name: 'Sam',
email: '[email protected]'
},
{
name: 'Ash',
email: '[email protected]'
}
].map((anObjectMapped, index) => {
return (
<p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
{anObjectMapped.name} - {anObjectMapped.email}
</p>
);
})
And remember when you put an array of jsx it has a different meaning and you can not just put object in your render method as you can put an array.
Take a look at my answer at mapping an array to jsx
这篇关于如何在 React 中映射对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
07-30 21:11