【问题标题】:How to use map inside map in React?如何在 React 中使用地图内的地图?
【发布时间】:2018-10-06 17:54:24
【问题描述】:

我有这样的对象:

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

我想将 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 将此表与标题和项目映射的正确语法是什么?

【问题讨论】:

  • 语法正确。但是您所指的变量rows不在范围内。
  • @Villemh 您能否更改标记的答案,因为标记的答案现在不正确?

标签: javascript reactjs


【解决方案1】:

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

  <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>

【讨论】:

  • 谢谢!我试图找到一种方法来访问同一地图函数中的行。有点混乱。这工作得很好。
  • @villemh 不确定这是否有意义,因为您基本上会将数组中每个元素的行堆叠在一起。看起来它与您的表头无关。
  • @vhflat 你完全正确。糟糕的是,我没有正确查看 OP 数据。我赞成你的回答:)
  • 我试图删除我的答案,但不幸的是我不能这样做,因为它接受了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2018-10-03
  • 1970-01-01
相关资源
最近更新 更多