【发布时间】: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。我不想定义所有类型的汽车并将它们作为道具发送到子组件。还是我应该这样?
请给我建议和解决方案。
【问题讨论】: