如何在React中映射对象数组 [英] How to map an array of objects in React

查看:57
本文介绍了如何在React中映射对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 :

我要映射的对象数组:

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
}

我想念什么?

推荐答案

您需要的是映射对象数组,并记住每个项目都是一个对象,因此您将使用点表示法来获取值物体.

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.

在您的组件中

 [
    {
        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数组时,它具有不同的含义,不能像放置数组那样将对象仅放置在render方法中.

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.

将数组映射到jsx

这篇关于如何在React中映射对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆