【发布时间】:2020-10-31 14:33:59
【问题描述】:
我正在尝试为chart.js 使用react-chartjs-2 的React 包装器。我不确定为什么我无法显示条形图。这可能是我为数据道具设置状态的方式。我要在图表中显示的 API 返回的数据采用以下格式:
[{packets: 14132, bytes: 743572434}, {packets: 10848, bytes: 824102247}, {packets: 7412, bytes: 1391125317}, {packets: 3978, bytes: 9107974}, ... , {packets: 4228, bytes: 8781508}]
我想用这个更新我的条形图状态中的数据道具,但不确定我是否做得对。当我在 render() 中 console.log this.state.barchart.datasets.data 时,它最初会作为一个空数组出现,然后填充适当的数据。当我登录this.state.barchart.labels 时,它总是会出现预期的标签。由于labels 已设置但data 未设置,我不确定问题出在哪里。我也不知道我是否设置了条件来显示条形图本身,因为有时this.state.barchart.datasets.data.length 会引发错误:TypeError: Cannot read property 'length' of undefined。
这是我的组件:
class Devices extends React.Component {
constructor(props) {
super(props);
this.state = {
barchart: {
labels: [],
datasets: [
{
label: "byte count",
backgroundColor: "rgba(75,192,192,1)",
borderColor: "rgba(0,102,204,1)",
borderWidth: 2,
data: [],
},
],
}
}
componentDidMount(){
all_hours = ["12:00 am", "1:00 am " ... "12:00 pm"]
fetch(API_URL)
.catch((error) => console.error("Error: ", error))
.then((data) => {
var barchart = {...this.state.barchart}
barchart.labels = all_hours // update the labels
barchart.datasets.data = data.map(x => { return x["bytes"]}) // update the data
this.setState({barchart})
})
render(){
return(
<div className="Line">
{typeof(this.state.barchart.datasets.data) !== "undefined"
&& this.state.barchart.datasets.data.length > 0? (
<Bar
data = {this.state.barchart}
options={{
title: {
display: true,
text: "Total Byte Count Per Hour",
fontSize: 20,
},
legend: {
display: true,
position: "right",
},
}}
/>
) : (
<div>Loading...</div>
)}
</div>
)
}
}
【问题讨论】:
标签: reactjs chart.js react-chartjs