我正在尝试从 ChartJS 中的 api 绘制加密货币。Axios 调用进展顺利,带有键值对的对象被获取。但是当我想 setState 将它们推入图表(数据属性)并且我正在记录我的状态时,它只返回两个空的数据集和标签数组
import React, { Component } from "react";
import Chart from "./components/Chart";
import axios from "axios";
class App extends Component {
state = {
chartData: {}
};
componentWillMount() {
this.getChartData();
}
getChartData() {
axios
.get(
"https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR"
)
.then(res => {
const coin = res.data;
const result = Object.values(coin)[0];
this.setState({
chartData: {
labels: [
"Boston",
"Worcester",
"Springfield",
"Lowell",
"Cambridge",
"New Bedford"
],
datasets: [
{
label: "Population",
data: result,
backgroundColor: [
"rgba(255, 99, 132, 0.6)",
"rgba(54, 162, 235, 0.6)",
"rgba(255, 206, 86, 0.6)",
"rgba(75, 192, 192, 0.6)",
"rgba(153, 102, 255, 0.6)",
"rgba(255, 159, 64, 0.6)",
"rgba(255, 99, 132, 0.6)"
]
}
]
}
});
});
console.log(this.state);
}
render() {
return (
<div className="App">
<Chart
chartData={this.state.chartData}
location="Massachusetts"
legendPosition="bottom"
/>
</div>
);
}
}
export default App;