在React JS中显示对象的数组列表

时间:2018-11-15 05:38:37

标签: javascript arrays reactjs

嗨,我在react js中有这个对象的列表数组,我不知道如何在渲染视图中显示。任何人都可以提出一个想法吗?

Post:{
  Store1: [
     0:{Id:"0001", Business:"Ministop"}
   ]
  Store2: [{
     0:{Id:"0002", Business:"Grocery Store"}
  }]
  Store3: [
     0:{Id:"0003", Business:"Seven Eleven"}
  ]
  Store4: [
     0:{Id:"0004", Business:"Big Store"},
     1:{Id:"0005", Business:"Medium Store"}
  ]
}

这是示例输出:

**Store 1**
   **Id      Business**
   0001    Ministop
**Store 2**
   **Id      Business**
   0002    Grocery Store
**Store 3**
   **Id      Business**
   0003    Seven Eleven
**Store 4**
   **Id      Business**
   0004    Big Store
   0005    Medium Store

我有这段代码,但有一个错误this.state.post.map不是函数

render() {
   const groupList = this.state.post.map((data, index) => {
       return  (
           <div key={index}>
              <div>{data}</div>
           </div>
       )
   });

   return (
     <div>{groupList}</div>
   )
} 

谢谢

2 个答案:

答案 0 :(得分:2)

这就是您的映射方式。只需使用this.state.post

更改帖子

const post = {
  Store1: [
    { Id: '0001', Business: 'Ministop' }
  ],
  Store2: [
    { Id: '0002', Business: 'Grocery Store' }
  ],
  Store3: [
    { Id: '0003', Business: 'Seven Eleven' }
  ],
  Store4: [
    { Id: '0004', Business: 'Big Store' },
    { Id: '0005', Business: 'Medium Store' }
  ]
};

console.log(Object.keys(post).reduce((acccumilator, iterator) => {
  return [...acccumilator, ...post[iterator]];
}, []));

/*
  Object.keys(this.state.post).reduce((acccumilator, iterator) => {
    return [...acccumilator, ...post[iterator]];
  }, []).map(data => {
    return  (
           <div key={data.id}>
              <div>{data.Business}</div>
           </div>
       )
  })
*/

答案 1 :(得分:1)

map不是对象的方法。您可以使用Object.keys映射其键。

render() {
   const groupList = Object.keys(this.state.post).map((key) => {
       return  (
           <div key={key}>
              <div>{this.state.post[key]}</div>
           </div>
       )
   });

   return (
     <div>{groupList}</div>
   )
}

但是,一旦您解决了其他问题,则应该尝试自己解决这些问题,并提出其他问题