无法使用react-chart-2在条形图中显示数据

Unable to display data in Bar Chart using react-chart-2

我正在尝试使用 react-chartjs-2 chart.js 的 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>
    )
  }
}

问题是您在错误的地方添加了数据。

barchart.datasets.data = data.map(x => { return x["bytes"]})

barchart.datasets 是一个包含您案例中的单个数据集的数组。因此,这应该改写如下:

barchart.datasets[0].data = data.map(x => { return x["bytes"]})

这可以通过以下方式简化:

barchart.datasets[0].data = data.map(x => x["bytes"])