【发布时间】:2021-09-16 20:15:39
【问题描述】:
我有 mainPrice 对象:
client_type: "individual"
large_car: {100: "3", 200: "2.5"}
medium_car: {100: "3", 200: "2.5"}
small_car: {100: "2.5", 200: "2.5"}
x_large_car: {100: "3", 200: "2.5"}
xx_large_car: {100: "3", 200: "2.5"}
我要做的是在输入框中显示每种类型的汽车。所以基本上我正在尝试映射它。比如small_car:
<td>
{Object.keys(mainPrice.small_car).map((key) => (
<tr>
<label>{key} miles: </label>
<InputPrice
mainPricePosts={mainPrice.small_car[key]}
handleChange={handleChange}
/>
</tr>
))}
</td>
但是我收到一个错误 TypeError: Cannot convert undefined or null to object 但是我不明白这个错误的原因。你能看看吗?
编辑:很多人说问题不在于地图,这就是为什么我想更多地解释代码。因此,在我的父组件上,我调用 API 来获取数据,然后用这些数据设置 MainPrice。最后就是这个对象:
client_type: "individual"
large_car: {100: "3", 200: "2.5"}
medium_car: {100: "3", 200: "2.5"}
small_car: {100: "2.5", 200: "2.5"}
x_large_car: {100: "3", 200: "2.5"}
xx_large_car: {100: "3", 200: "2.5"}
因此,我将此数据作为道具发送到当前组件,并尝试将这些数据显示到文本框中。
所以这里是组件:
const PricePostsIndividual = ({ mainPrice }) => {
console.log({ mainPrice })
return (
<>
<tbody className="price_coefficient">
<td>
{/* {Object.keys(mainPrice.small_car).map((key) => (
<tr>
<label>{key} miles: </label>
<InputPrice
mainPricePosts={mainPrice.small_car[key]}
handleChange={handleChange}
/>
</tr>
))} */}
</td>
</tbody>
</>
);
};
export default PricePostsIndividual;
如你所见,我评论了 iside of 并且 mainProce 在这种情况下是正确的。
以及父组件:
export default function PriceCoefficient() {
const [mainPrice, setMainPrice] = useState({})
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
const fetchPosts = async () => {
try {
setLoading(true);
const res = await Axios({
method: "POST",
url: `url`,
headers: {
"cache-Control": "no-cache",
"content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
if (res.status === 200) {
setMainPrice(res.data.main_price);
}
setLoading(false);
} catch (err) {
setError(err.message);
setLoading(false);
}
};
fetchPosts();
}, []);
return (
<>
<PanelHeader size="sm" />
<div className="content">
<Row>
<Col xs={12}>
<Card>
<CardBody>
<h4>Main Prices</h4>
<Table responsive>
<thead className="text-primary">
<tr>
<th>Small Cars</th>
</tr>
</thead>
<PricePostsMainPrice
mainPrice={mainPrice}
loading={loading}
error={error}
/>
</Table>
</CardBody>
</Card>
</Col>
</Row>
</div>
</>
);
}
谢谢...
【问题讨论】:
-
假设你到处使用snake_case,
mainPrice是这样还是应该是main_price? -
试试这个 -->
Object.keys(mainPrice?.small_car || {}) -
可能 mainPrice 在调用此函数时没有完整的数据。使用 console.log 检查,如果您仍然需要帮助,请添加更多代码。
-
我看不出问题使用此代码可能问题出在其他地方并在这里体现出来。请尝试更新您的问题以包含Minimal, Complete, and Reproducible Code Example。
-
@Prusdrum maiinPrice 是我在问题中给出的对象。我通过获取数据来实现。
标签: reactjs object input mapping