【问题标题】:How can i iterate this json with map in React to render it我如何在 React 中用 map 迭代这个 json 来渲染它
【发布时间】:2017-03-02 05:23:02
【问题描述】:

我正在尝试迭代这个 JSON,以便我可以制作一个表格,但是由于有很多标题和很多数据,我怎么能不这样做。

 const BBDDCustomer = {
      ui_labels: {
        name: 'Name',
        address: 'address',
        postalCode: 'Postal Code',
        city: 'City',
        country: 'Country',
        telephone: 'Telephone',
        email: 'Email',
        modified: 'Modified',
        delete: 'Delete'

      },
  data: [
    {
      name: 'n1',
      address: 'a1',
      postalCode: 'PC 1',
      city: 'c 1',
      country: 'cou 1',
      telephone: 'tel 1',
      email: 'em 1'
    }
}

我不必这样写:

<table striped bordered condensed hover responsive>
      <thead>
       <tr>
         <th>{BBDDCustomer.ui_labels.name}</th>
         <th>{BBDDCustomer.ui_labels.address}</th>
         <th>{BBDDCustomer.ui_labels.postalCode}</th>
         <th>{BBDDCustomer.ui_labels.city}</th>
         <th>{BBDDCustomer.ui_labels.country}</th>
         <th>{BBDDCustomer.ui_labels.telephone}</th>
         <th>{BBDDCustomer.ui_labels.email}</th>
         <th>{BBDDCustomer.ui_labels.modified}</th>
         <th>{BBDDCustomer.ui_labels.delete}</th>
       </tr>  
</table> 

【问题讨论】:

  • 这不是 JSON > what?
  • 您可以将Object.keysmap 结合使用。但不保证属性的顺序。
  • 答案就在问题中,不是吗?映射您的结构并渲染。你需要学会做出反应来做到这一点

标签: javascript json reactjs


【解决方案1】:

你需要按照你想要的顺序枚举属性

const columns = ['name', 'address', ...];

并使用map

<Table striped bordered condensed hover responsive>
      <thead>
       <tr>
           {
             columns.map(column => (
              <th key={column}>{BBDDCustomer.ui_labels[column]}</th>
            ))
           }
       </tr>
      </thead>
      <tbody>
        {
          BBDDCustomer.data.map((data, i) =>(
           <tr key={i}>
               {
                 columns.map(column => (
                    <td key={column + i}>{data[column]}</td>
                 ))
               }
           </tr>
          ))
        }
      </tbody>
</Table> 

【讨论】:

猜你喜欢
  • 2018-07-21
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多