在React中如何在map内使用map?

时间:2018-10-06 17:54:24

标签: javascript reactjs

我有这样的对象

[{{a:1,行:[]},{a:2,行:[]}]

我想将a映射为表的列并将行映射为单元格。

我正在尝试这样:

  <thead>
    <tr>
      {doc.map(({
        _id, rfqID, supplier, notes, rows,
      }) => (
          <th>{supplier}</th>
        ))}
    </tr>
  </thead>
  <tbody>
    {rows.map(({ offerPrice }) => (
      <tr>
        <td>1</td>
        <td>{offerPrice}</td>
      </tr>
    ))}
  </tbody>

但是我得到Uncaught ReferenceError: rows is not defined 将表与标题和项目映射的正确语法是什么?

1 个答案:

答案 0 :(得分:4)

由于doc是对象数组,因此您需要在doc上进行映射,然后再次在行上进行映射以显示offerprice

  <thead>
    <tr>
      {doc.map(({
        _id,
        rfqID,
        supplier,
        notes,
        rows,
      }) => 
        <th key={_id}>{supplier}</th>
      )}
    </tr>
  </thead>
  <tbody>
  {doc.map(({ rows }) => 
    rows.map((offerPrice, index)  =>
      <tr key={`Key-$(index)`}>
        <td>1</td>
        <td>{offerPrice}</td>
      </tr>)
  )}
  </tbody>