如果数据不存在,则在图表中显示 'undefined%'

Showing 'undefined%' in the graph if data does not exist

我有这张图,对于不存在的数据,它会显示“undefined%”。

如果数据不存在,如何去掉“undefined%”并在图表中不显示任何内容?

代码如下:

import { Bar } from "react-chartjs-2";

import "chartjs-plugin-datalabels";
import { Chart } from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";

Chart.register(ChartDataLabels);


 <Bar
          data={{
            labels,
            datasets: //datasets here
          }}
          options={{
            scales: {
              y: {
                min: 0,
                max: 100,
                ticks: {
                  stepSize: 20,
                  callback: function (value) {
                    return ((value / this.max) * 100).toFixed(0) + "%"; 
                  },
                },
              },
            },
            plugins: {
              tooltip: {
                callbacks: {
                  label: function (context) {
                    var label = context.dataset.label || "";
                    if (context.parsed.y !== null) {
                      label += " " + context.parsed.y + "%";
                    }
                    return label;
                  },
                },
              },
              datalabels: {
                formatter: (val, context) => `${val}%`,
              }, // for the label percentage symbol inside the graph
            },
          }}
        />

您可以使用 if 语句检查 val 是否存在

datalabels: {
    formatter: (val, context) => {
        if(val) return `${val}%`
        return;
    },
  }, // 

如果您只想在未定义(或任何虚假语句)的情况下显示 0,您可以使用 || 运算符。

datalabels: {
                formatter: (val, context) => `${val || 0}%`,
              }

问题似乎出在这一行:return ((value / this.max) * 100).toFixed(0) + "%"; 里面有些东西,可能 valueundefined 左右。您可以有条件地不显示任何内容,例如return value ? ((value / this.max) * 100).toFixed(0) + "%" : null;