开发者问题收集

Chart.js 无法使用数据 reactjs 呈现图表

2018-10-09
205

我正在尝试使用 chartjs-2 来呈现带有数据的条形图。这是我的代码:

import React from "react";
import { Bar, Line, Pie } from "react-chartjs-2";

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      chartData: {
        labels: ["Nike", "Adidas", "Louis", "Champion", "Yeezy", "Versace"],
        datasets: [
          {
            label: "Sales",
            data: [34, 24, 4, 10, 18, 9],
            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)"
            ]
          }
        ]
      }
    };
  }

  setChartData(labels1, data1) {
    //Pull from API here
    this.setState({
      chartData: {
        labels: labels1,
        datasets: [
          {
            label: "Sales",
            data: data1,
            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)"
            ]
          }
        ]
      }
    });
    return this.state.chartData;
  }

  render() {
    var data1 = [4, 4, 14, 10, 16, 9]
    var label1 = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth"] 
    console.log(() => this.setChartData(label1, data1))
    return (
      <Bar
        data = {() => this.setChartData.bind(this, label1, data1)}
        width = {100}
        height = {75}
        options = {{
          legend: {
            display: !this.props.displayLegend
          }
        }}/>
    );
  }

每当我运行它时,您都可以看到网格,但没有条形图(应该是条形图)。如果我将 render() 方法中的 data 替换为 this.state.chartData 而不是 () => this.setChartData.bind(this, label1, data1) ,它会显示在构造函数中创建的图表,但我希望它显示在 setChartData 方法中创建的图表。任何帮助都将不胜感激。谢谢!

1个回答

render() 方法应为纯函数,这意味着它不应直接更改组件状态。您应该在生命周期方法(例如 componentDidMount() )或自定义方法(事件处理程序)中更改状态,在渲染过程中的某个时刻调用该方法。

这里有一个 CodeSandbox 演示了这个想法。

我建议您浏览 生命周期方法 ,并找出最适合您目的的方法。

Franklin Farahani
2018-10-09