在点击事件中删除图表会产生空错误的'removeHoverStyle'

问题描述 投票:1回答:1

我的基本图表包装看起来像这样(将ReactJS 16.8+与ChartJS 2.0+一起使用)

import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import Chart from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { makeStyles } from '@material-ui/styles';
import { useTranslation } from 'react-i18next';

Chart.plugins.unregister(ChartDataLabels);
function BarChart({ chartId, options }) {
  const classes = useStyles();
  const { t } = useTranslation();

  useEffect(() => {
    const myChart = new Chart(chartId, options); // instantiate a new chart
    return () => {
      myChart.destroy(); // destroy chart on component unmount
    };
  });

  return (
    <canvas className={classes.chart} id={chartId} data-testid={chartId}>
      <p>{t('noCanvasSupport')}</p>
    </canvas>
  );
}

我传递的选项对象具有一个onClick回调函数,该函数会更改父对象的状态变量之一(布尔值)。这将有条件地呈现以下图表之一。

function Parent() {
...
return (
<>
    {isTrue && <Barchart options={{...}} chartId={'chart-1'} />} // throws error as soon as isTrue becomes false
    {!isTrue && <Barchart options={{...}} chartId={'chart-2'} />}
</>
)
}

我似乎在更改isTrue(通过单击图表中的一个条形时触发的onclick回调函数)并卸载了第一个Barchart时收到此错误。由于某种原因,调用了removeHoverStyle

错误:

Uncaught TypeError: Cannot read property 'removeHoverStyle' of null
    at Chart.updateHoverStyle (Chart.js:8801)
    at Chart.handleEvent (Chart.js:8883)
    at Chart.eventHandler (Chart.js:8820)
    at listener (Chart.js:8758)
    at HTMLCanvasElement.proxies.<computed> (Chart.js:6685)

选项对象:

const options = {
    type: 'horizontalBar',
    plugins: [ChartDataLabels],
    data: data,
    options: {
      onClick: handleChartClick,
      maintainAspectRatio: false,
      cornerRadius: 6,
      tooltips: {
        enabled: true,
        callbacks: {
          label: (tooltipItem, data) => {
            let label = data.datasets[tooltipItem.datasetIndex].label || '';
            if (label) {
              label += ': ';
            }
            label += `${(tooltipItem.xLabel * 100).toFixed(1)}%`;
            return label;
          },
        },
      },
      legend: {
        position: 'bottom',
        labels: {
          fontFamily: 'Roboto',
          fontSize: theme.spacing(2) - 2,
          boxWidth: theme.spacing(2) + 2,
        },
      },
      plugins: {
        datalabels: {
          align: context => {
            if (isSmallScreen && context.datasetIndex === 1 && context.dataset.data[context.dataIndex] < 0.1) {
              return 'start';
            } else {
              return 'start';
            }
          },
          anchor: 'end',
          color: '#000000',
          font: {
            size: theme.spacing(1) + 4,
            family: 'Roboto',
            weight: 'normal',
          },
          formatter: (value, context) => {
            return (value * 100).toFixed(1) + '%';
          },
          display: context => {
            return context.dataset.data[context.dataIndex] > 0.05;
          },
        },
      },
      scales: {
        xAxes: [
          {
            stacked: true,
            scaleLabel: {
              display: false,
            },
            gridLines: {
              display: false,
              drawBorder: false,
            },
            ticks: {
              display: false,
            },
          },
        ],
        yAxes: [
          {
            stacked: true,
            gridLines: {
              display: false,
              drawBorder: false,
            },
            ticks: {
              fontSize: isHeader ? theme.spacing(3) : theme.spacing(2),
              fontFamily: 'Roboto',
              fontStyle: isHeader ? 'bold' : 'normal',
              padding: theme.spacing(2),
            },
          },
        ],
      },
    },
  };

相关链接https://github.com/chartjs/Chart.js/issues/3777

javascript reactjs chart.js
1个回答
0
投票

我有完全相同的问题,我发现我们不应该在onClick事件处理程序中修改图表,而解决方法是

        window.setTimeout(function () {
            if (ref.current) {
                ref.current.chartInstance.destroy();
            }
            history.push(`/eod/${date}`);
        }, 1);
© www.soinside.com 2019 - 2024. All rights reserved.