Chartjs破坏方法不影响图表

时间:2018-01-12 10:02:09

标签: javascript reactjs chart.js chart.js2

您好我在我的反应应用程序中有这个代码:

this.chart = new Chart(node, options);
// adding data to the chart ...
this.chart.destroy();
this.chart = null;
this.chart = new Chart(node, options);
// adding data to the chart ...

第二次添加数据后,第一个数据集仍显示在图表上。我也试过删除画布节点,但我得到了相同的结果。任何人都知道为什么会发生这种情况?

1 个答案:

答案 0 :(得分:2)

var ctx = document.getElementById("barChart");
var barChart = new Chart(ctx, {
type: 'bar',
data: {
    labels: ["Dog", "Cat", "Pangolin"],
    datasets: [{
              backgroundColor: '#00ff00',
        label: '# of Votes 2016',
        data: [12, 19, 3]
        }]
    }
});

function addData(chart, label, color, data) {
  chart.data.datasets=[];
    chart.data.datasets.push({
    label: label,
  backgroundColor: color,
  data: data
});
chart.update();
}

// 2秒后更改新数据集

setTimeout(function() {
   addData(barChart, '# of Votes 2017', '#ff0000', [16, 14, 8]);
 }, 2000);
相关问题