首页 > 解决方案 > 如何显示一个数组,其中数组中的每个对象都是 ReactJS 中的新对象

问题描述

我有一个包含多个对象的数组,如下所示:

const locations = [
  {
     information: ["Data Analyst", "Uruguay", "Montevideo", "$30,000"],
  },
  {
     information: ["CTO", "UK", "Manchester", "$75,000"],
  }
];

我想在包含<td>每个字符串的新表行中显示每个数组。

目前我已经这样做了:

<tr>
   {locations.map((location) => <td>{location.information}</td>)};
</tr>

它返回每条信息<td>

这是当前数据的样子: 在此处输入图像描述

以及它的外观 在此处输入图像描述

标签: reactjsecmascript-6

解决方案


更改代码,

<tr>
   {locations.map((location) => <td>{location.information}</td>)};
</tr>

至:

<table border="1" width="100%" className="component_useRefBox">
  <tbody>
    {locations.map((location, i) => {
      return (
        <tr key={i}>
          {location.information.map((data, j) => {
            return <td key={j}> {data} </td>;
          })}
        </tr>
      );
    })}
  </tbody>
</table>

要逐行显示两条记录,您需要将标签移到{locations.map((location) .... )}上方<tr> ... </tr>,因为在使用map方法时,只有每一行会被迭代,并且您将得到两个单独的行。

{locations.map((location, i) => {
          return (
            <tr>
                ....
            </tr>
 )})}

location.information数组数据一样,您不能直接分配它。

您需要使用地图进行迭代并显示每个数据,例如,

{location.information.map((data) => {
   return <td> {data} </td>;
})}

编辑 React 功能组件(分叉)


推荐阅读