如何在 React 中映射对象数组

编程入门 行业动态 更新时间:2024-10-25 10:33:16
本文介绍了如何在 React 中映射对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个对象数组.我想映射这个对象数组.我知道如何映射数组,但不知道如何映射对象数组.这是我到目前为止所做的:

我要映射的对象数组:

const theData = [{名称:山姆",电子邮件:'somewhere@gmail'},{名称:'灰',电子邮件:'something@gmail'}]

我的组件:

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:数据数组}

我错过了什么?

解决方案

你需要映射你的对象数组并记住每个项目都是一个对象,这样你就可以使用例如点符号来获取值对象.

在你的组件中

[{名称:山姆",电子邮件:'somewhere@gmail'},{名称:'灰',电子邮件:'something@gmail'}].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: 'somewhere@gmail' }, { name: 'Ash', email: 'something@gmail' } ]

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: 'somewhere@gmail' }, { name: 'Ash', email: 'something@gmail' } ].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 中映射对象数组

本文发布于:2023-11-26 17:29:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634512.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   如何在   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!