在react js中在tbody中显示对象的最佳方式

时间:2021-04-07 11:13:45

标签: reactjs

我有一个对象数组,如何在表格中显示地图的地图?

const row = [{
    "index": 5399,
    "name": "user name",
    "quantity": "1000",
    "remainingQty": 2000,
    "budgetedCost": [
        {
            "Labour Cost": "177000"
        },
        {
            "Material Cost": "177000"
        }
    ],
    "amountForQuantity": [
        {
            "key": "Labour Cost",
            "value": 177000
        },
        {
            "key": "Material Cost",
            "value": 177000
        }
    ],
}];

在 JSX 中,

{row?.map((x, i) => {
    return (
    .... other code

    <tbody>
        {
            (x.amountForQuantity)?.map((cost) => {
                (x.budgetedCost)?.map((budget) => {
                return (
                    <td>{budget.key}</td>
                    <td>{cost}</td> // how to print cost objects values here ?
                );
            }})
         }

如何打印成本值?当我运行这个时,tbody 不显示,只显示thead。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您在此处返回多个元素,React 不支持该元素。使用片段:

return (
    <td>{budget.key}</td>
    <td>{cost}</td> // how to print cost objects values here ?
);

将它们括在 <></> 中,而不是上面的代码:

return (
  <>
    <td>{budget.key}</td>
    <td>{cost}</td> // this is the way to print cost objects values here!
  </>
);

好的,为了得到完美的结果,我做了这样的事情:

export default function App() {
  const row = [
    {
      index: 5399,
      name: "user name",
      quantity: "1000",
      remainingQty: 2000,
      budgetedCost: [
        {
          "Labour Cost": "177000"
        },
        {
          "Material Cost": "177000"
        }
      ],
      amountForQuantity: [
        {
          key: "Labour Cost",
          value: 177000
        },
        {
          key: "Material Cost",
          value: 177000
        }
      ]
    }
  ];
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <table>
        <thead>
          <tr>
            <th>Param</th>
            <th>Value</th>
            <th>Param</th>
            <th>Value</th>
          </tr>
        </thead>
        {row?.map((x, i) => {
          return (
            <tbody>
              {x.amountForQuantity?.map((cost) => {
                return x.budgetedCost?.map((budget) => {
                  return (
                    <tr>
                      <th>{cost.key}</th>
                      <td>{cost.value}</td>
                      <th>{Object.keys(budget)[0]}</th>
                      <td>{Object.values(budget)[0]}</td>
                    </tr>
                  );
                });
              })}
            </tbody>
          );
        })}
      </table>
    </div>
  );
}

查看输出:https://usr98.csb.app/

预览

preview

相关问题