【发布时间】:2021-09-30 13:50:48
【问题描述】:
我正在尝试获取 JSON 数据并将其传递到我的“HistoryChart”组件中,以尝试将日期和价格映射到两个数组中,以便我可以在图表上显示它们。但是,我不断收到未定义的错误。
这是 JSON 数据:
{
"_id": 1,
"name": "",
"brand": "",
"image": "",
"sources": [],
"history": [
{
"_id": 3,
"price": "299.99",
"product": 1,
"date": "2021-07-01"
},
{
"_id": 4,
"price": "399.99",
"product": 1,
"date": "2021-07-08"
},
{
"_id": 5,
"price": "499.99",
"product": 1,
"date": "2021-07-15"
},
{
"_id": 6,
"price": "599.99",
"product": 1,
"date": "2021-07-22"
},
{
"_id": 7,
"price": "699.99",
"product": 1,
"date": "2021-07-29"
}
]
}
这是我的 HistoryChart 组件:
function HistoryChart({product}) {
var dates = product.history.map(function(e){ //<-- The Problem lies here where it says cannot map undefined.
return e.date;
});
var prices = product.history.map(function(e){
return e.price;
});
return (
<div>
<Line
data={{
labels: dates,
datasets: [{
label: `Average Price History (ID: ${product._id})`, //<-- This part works
backgroundColor:/* 'transparent' */ '#00ad0e',
borderColor: '#00ad0e',
data: prices,
}]
}}
width={100}
height={50}
options={{ maintainAspectRatio: true }}
/>
</div>
)
}
我也在使用 redux 来获取数据:
const productDetails = useSelector(state => state.productDetails)
const {error, loading, product} = productDetails
数据像这样传递到 HistoryChart 组件中:
<HistoryChart product={product}/>
任何帮助将不胜感激,谢谢。
【问题讨论】:
-
你确定你传递了正确的对象吗?也许你正在将它包装在另一个中。你能在
HistoryChart()中console.log(product)吗?
标签: javascript arrays reactjs redux charts