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

前端之家收集整理的这篇文章主要介绍了数组 – 如何在React中映射对象数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个对象数组.我想映射这个对象数组.我知道如何映射数组,但无法弄清楚如何映射对象数组.这是我到目前为止所做的:

我要映射的对象数组:

  1. const theData = [
  2. {
  3. name: 'Sam',email: 'somewhere@gmail.com'
  4. },{
  5. name: 'Ash',email: 'something@gmail.com'
  6. }
  7. ]

我的组件:

  1. class ContactData extends Component {
  2. render() {
  3. //works for array
  4. const renData = this.props.dataA.map((data,idx) => {
  5. return <p key={idx}>{data}</p>
  6. });
  7.  
  8. //doesn't work for array of objects
  9. const renObjData = this.props.data.map(function(data,idx) {
  10. return <p key={idx}>{data}</p>
  11. });
  12.  
  13. return (
  14. <div>
  15. //works
  16. {rennData}
  17. <p>object</p>
  18. //doesn't work
  19. {renObjData}
  20. </div>
  21. )
  22. }
  23. }
  24.  
  25.  
  26. ContactData.PropTypes = {
  27. data: PropTypes.arrayOf(
  28. PropTypes.obj
  29. ),dataA: PropTypes.array
  30. }
  31.  
  32. ContactData.defaultProps = {
  33. data: theData,dataA: dataArray
  34. }

我错过了什么?

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

在您的组件中

  1. [
  2. {
  3. name: 'Sam',email: 'something@gmail.com'
  4. }
  5. ].map((anObjectMapped,index) => {
  6. return (
  7. <p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
  8. {anObjectMapped.name} - {anObjectMapped.email}
  9. </p>
  10. );
  11. })

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

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

猜你在找的React相关文章