【问题标题】:JSON map object to the table in ReactJSON 将对象映射到 React 中的表
【发布时间】:2021-09-04 10:16:09
【问题描述】:

我有一个这样的 JSON,我想在 React 的表中显示这个 JSON。

{
  "Status": true, 
  "discounts": { 
    "individual": {
      "number_of_cars_discount": {
        "1": "1", 
        "10": "1", 
        "2": "0.98", 
      }
    }
  }, 
  "main_price": {
    "client_type": "individual", 
    "large_car": {
      "100": "3", 
      "1000": "0.9", 
      "100000": "0.60", 
    }, 
  }
}

为此,我定义了

const [mainPrice, setMainPrice] = useState({});

在父组件中,我这样获取它:

setMainPrice(res.data.main_price);

我将 mainPrice 发送到要在表中显示 JSON 的子组件:

<tbody>
          <tr>
            <td>
            {Object.keys(individualPosts).map((key) => (
              <tr>
                <td key={key}>{individualPosts[key]}</td>
              </tr>
            ))}
            </td>
            <td>
            {Object.keys(mainPrice.large_car).map((key) => (
              <tr>
                <td key={key}>{mainPrice.large_car[key]}</td>
              </tr>
            ))}
            </td>
          </tr>
        </tbody>

但它给了我一个错误:TypeError: Cannot convert undefined or null to object

但我不知道为什么。

我有其他类型的汽车,例如 large_cars、small_cars,所以我需要像这样采用 mainPrice。我不想定义所有类型的汽车并将它们作为道具发送到子组件。还是我应该这样?

请给我建议和解决方案。

【问题讨论】:

    标签: json reactjs object


    【解决方案1】:

    在这种情况下需要进行空检查以避免错误。

    试试这个

    <td>
      {Object.keys(mainPrice?.large_car).length > 0 && Object.keys(mainPrice?.large_car).map((key) => (
       <tr>
        <td key={key}>{mainPrice.large_car[key]}</td>
       </tr>
      ))}
    </td>
    

    【讨论】:

    • 我收到 TypeError: Cannot convert undefined or null to object 但事情是 mainPrice is not null
    猜你喜欢
    • 2019-05-27
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 2014-11-07
    • 2017-12-24
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    相关资源
    最近更新 更多