我正在从API接收数据,我想获取该数据并将其填充到我的图表中。我可以看到在哪里调用了API数据并将其传递到setState中,但是似乎无法正确获取此数据并将其传递到图表中。
我尝试使用Chart.js的destroy()和update()方法无效。我确定这只是我在应用程序中未正确使用它们的问题。下面的代码不包含那些方法,因为我不确定在哪里使用它们。我也尝试过将API数据推入图表的数据数组中,但没有走运。
componentDidMount() {
// create chart
new Chart(myChartRef, {
type: "line",
data: {
labels: ["Jan", "Feb", "March"],
datasets: [
{
data: this.state.chartData,
backgroundColor: gradient,
pointBackgroundColor: "#fff",
pointBorderColor: gradient,
pointRadius: "5",
hoverBackgroundColor: "#75C6FF",
hoverBorderColor: gradient
}
]
},
options: {
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [
{
gridLines: {
color: "#535356"
},
ticks: {
fontColor: "#87889C"
}
}
],
yAxes: [
{
gridLines: {
color: "#535356"
},
ticks: {
fontColor: "#87889C"
}
}
]
}
}
});
/* fetch API data and use it to set app state (setState) */
const getChartData = () => {
fetch(
"https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD"
)
.then(response => {
return response.json();
})
.then(myJson => {
const bitcoinPrice = myJson.BTC.USD;
this.setState({ chartData: bitcoinPrice });
console.log(JSON.stringify(myJson));
});
};
getChartData();
}
在代码中,一旦安装了组件,便创建了一个新图表。然后,我调用API并接收要显示在图表上的数据。我可以在React开发工具中看到状态已在我的应用程序中设置,但图表未更新。我认为我需要做一些类似的事情,例如将API数据映射到图表中的数据数组中,但是我不确定如何正确执行此操作,因此我对SO或在线其他任何地方建议的其他解决方案都不满意。
这是我的第一个React应用程序,所以不确定在React或Chart.js中是否做错了什么?
根据我的经验,您可以将图表组件和图表容器分开。在图表容器中进行获取,并将获取的数据作为道具传递给图表组件,以更好地组织代码。
另外,您还需要检查图表组件内部的componentWillReceiveProps生命周期方法是否更改了道具,并相应地更新了图表
import React, { Component } from 'react';
import ChartComponent from './ChartComponent'
export class ChartContainer extends Component {
constructor(props) {
super(props);
this.state = {
chartData: []
}
componentDidMount() {
fetch(
"https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD"
)
.then(response => {
return response.json();
})
.then(myJson => {
const bitcoinPrice = myJson.BTC.USD;
this.setState({ chartData: bitcoinPrice });
console.log(JSON.stringify(myJson));
});
}
render() {
const { chartData } = this.state;
return (
<ChartComponent chartData={chartData}/ >
);
}
}
import React, { Component } from 'react';
export class ChartComponent extends Component {
constructor(props){
super(props)
this.state = { chart : null }
}
chart = React.createRef();
componentDidMount(){
// pass chartData to Chart below as this.props.chartData
let theChart = new Chart(...)
// set chart to state
this.setState({ chart: theChart })
}
componentWillReceiveProps(nextProps, nextContext) {
// update chart according to prop change
this.state.chart.data.datasets.forEach((dataset) => {
dataset.data.push(nextProps.chartData);
});
this.state.chart.update();
}
render(){
return (
<canvas id="myChart" ref={this.chart} />
);
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句