首页 > 解决方案 > 在 ComponentDidMount 中添加条件以显示图表数据

问题描述

我在 componentDidMount 中添加了一个条件,以根据收到的专业人士展示 1 个或 2 个数据集的数据。但是,我在 if 条件下遇到错误。这是 BarChart 组件。在其中,我已经从“chart.js”导入了图表。

class BarChart1 extends Component {
constructor(props) {
    super(props);
}
chartRef = React.createRef();

componentDidMount() {
    const myChartRef = this.chartRef.current.getContext("2d");
    let dataCheck = null;
    if(this.props.data2){
        let dataCheck = {
            labels: this.props.labels,
            datasets: [
                {
                    label: this.props.label1,
                    backgroundColor: 'rgba(26,179,148,0.5)',
                    borderColor: "rgba(26,179,148,0.7)",
                    data: this.props.data1
                }, {
                    label: this.props.label2,
                    backgroundColor: 'rgba(220, 220, 220, 0.5)',
                    pointBorderColor: "#fff",
                    data: this.props.data2
                }
            ]
        }
    }
    else {
        let dataCheck = {
            labels: this.props.labels,
            datasets: [
                {
                    label: this.props.label1,
                    backgroundColor: 'rgba(26,179,148,0.5)',
                    borderColor: "rgba(26,179,148,0.7)",
                    data: this.props.data1
                }
            ]
        }
    }
    new Chart(myChartRef, {
        type: 'bar',
        data: {dataCheck},
        options: {
            responsive: true,
            maintainAspectRatio: false,
            legend: {
                display: true,
            },
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    },
                    gridLines: {
                        display: false
                    }
                }],
                xAxes: [{
                    gridlines: {
                        display: false
                    },
                    ticks: {
                        fontSize: 9
                    }
                }]
            }
        },
        plugins: [{
            beforeInit: function(chart) {
               chart.data.labels.forEach(function(e, i, a) {
                  if (/\n/.test(e)) {
                     a[i] = e.split(/\n/);
                  }
               });
            }
     }]
    })
}

render() {
    return <canvas ref={this.chartRef} />
}

}

我已经编辑了我的问题。我现在得到一个没有错误的空白图表。

在此处输入图像描述

标签: javascriptreactjschart.js

解决方案


您的代码中有两个错误。

  1. 你必须用 ; 结束变量声明 代替 ,
  2. 您必须在 if else 块之外声明 datacheck ,除非您希望它未定义

    componentDidMount() {
                ...
                let dataCheck;
                if(this.props.data2){
                     dataCheck = {
                       ...
                    }
                }
                else {
                    dataCheck = {
                      ...
                    }
        }
    }


推荐阅读