加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – 如何在React中映射对象数组

发布时间:2020-12-15 20:44:00 所属栏目:百科 来源:网络整理
导读:我有一个对象数组.我想映射这个对象数组.我知道如何映射数组,但无法弄清楚如何映射对象数组.这是我到目前为止所做的: 我要映射的对象数组: const theData = [ { name: 'Sam',email: 'somewhere@gmail.com' },{ name: 'Ash',email: 'something@gmail.com' }
我有一个对象数组.我想映射这个对象数组.我知道如何映射数组,但无法弄清楚如何映射对象数组.这是我到目前为止所做的:

我要映射的对象数组:

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: 'something@gmail.com'
    }
].map((anObjectMapped,index) => {
    return (
        <p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
            {anObjectMapped.name} - {anObjectMapped.email}
        </p>
    );
})

并且记住,当你放置一个jsx数组时,它有不同的含义,你不能只在你的渲染方法中放置对象,因为你可以放一个数组.

在mapping an array to jsx看一下我的回答

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读