我对web开发有点陌生,在尝试使用chartjs中的甜甜圈图来可视化数据时遇到了一个问题。
useEffect(() => {
const fetchAPI = async() => {
const resp = await httpClient.get("//localhost:5000/dashboard")
const data = resp.data
// console.log("From fetchapi", Object.values(data).map((crypto) => crypto.current))
const keys_list = Object.keys(data).map((crypto) => crypto)
const data_list = Object.values(data).map((crypto) => crypto.current)
//console.log(data_list)
setChartData({
labels: keys_list,
datasets: [
{
label: 'Price in KRW',
data: data_list,
backgroundColor: [
"#ffbb11",
"#ecf0f1",
"#50AF95"
]
}
]
});
};
fetchAPI()
}, []);
const [chartData, setChartData] = useState({})
return(
<div><Doughnut data = {chartData}</div>
)
data
是这样的{'eth': {'available': '0.5', 'current': '890'}, 'ada': {'available': '43.9', 'current': '24'}}
所以我试着把数据作为数据。当前,这里是['890','24'],标签是['eth', 'ada']然而,我得到一个未捕获的TypeError:不能读取未定义的属性(读取'map')错误。
任何帮助将非常感激!
您的数据是异步的。在页面加载时,在数据到达之前数据是未定义的。像这样添加询问点,这意味着如果数据存在就制作一个映射
useEffect(() => {
const fetchAPI = async() => {
const resp = await httpClient.get("//localhost:5000/dashboard")
const data = resp.data
// console.log("From fetchapi", Object.values(data).map((crypto) => crypto.current))
if(data){
const keys_list = Object.keys(data).map((crypto) => crypto)
const data_list = Object.values(data).map((crypto) => crypto.current)
//console.log(data_list)
setChartData({
labels: keys_list,
datasets: [
{
label: 'Price in KRW',
data: data_list,
backgroundColor: [
"#ffbb11",
"#ecf0f1",
"#50AF95"
]
}
]
});
}
};
fetchAPI()
}, []);