How to fix Uncaught Error: This method is not implemented in react-chartjs-2

How to fix Uncaught Error: This method is not implemented in react-chartjs-2

我正在使用 react-chartjs-2 创建折线图。在那个 grpah 中,我想在 xAxes 中使用时间。但是我收到以下错误。

Chart.js:10609 Uncaught Error: This method is not implemented: either no adapter can be found or an incomplete integration was provided

这是我的代码。

render() {
    var startDate = moment().subtract(1, 'year').format('MMM YYYY');
    var endDate = moment().format('MMM YYYY');
    const data = {
      labels: [startDate, endDate],
      datasets: [
        {
          label: 'NPS Score',
          fill: false,
          lineTension: 0.2,
          backgroundColor: 'rgba(75,192,192,0.4)',
          borderColor: 'rgba(75,192,192,1)',
          borderDash: [],
          borderDashOffset: 0.0,
          pointBorderColor: 'rgba(75,192,192,1)',
          pointBackgroundColor: '#fff',
          pointBorderWidth: 1,
          pointHoverRadius: 5,
          pointHoverBackgroundColor: 'rgba(75,192,192,1)',
          pointHoverBorderColor: 'rgba(220,220,220,1)',
          pointHoverBorderWidth: 2,
          pointRadius: 1,
          pointHitRadius: 10,
          data: this.state.data,
        },
      ],
    };

    const lineOptions = {
      scales: {
        xAxes: [
          {
            type: 'time',
            time: {
              unit: 'month',
              tooltipFormat: 'lll',
            },
            ticks: {
              maxTicksLimit: 12,
            },
          },
        ],
        yAxes: [
          {
            stacked: true,
            gridLines: {
              display: false,
            },
            ticks: {
              suggestedMin: 100,
              suggestedMax: 0,
            },
          },
        ],
      },
      legend: {
        display: false,
      },
      tooltips: {
        enabled: true,
      },
    };
    return <Line data={data} options={lineOptions} height={120} />;

我找不到解决这个问题的方法。有一些问题有相同的错误,但不是 react js。谁能帮我这个。提前致谢。

问题出在 moment.js。较新的版本有问题。最好的办法是降级 moment.js 版本。这是我解决这个问题的方法。

1) 在 package.json

中更新您的依赖项版本
"dependencies": {
    "chart.js": "2.9.3",
    "moment": "2.24.0",
    "moment-timezone": "^0.5.28",
    "react-chartjs-2": "2.9.0",
 }

2) 在package.json

中添加如下代码
"resolutions": {
    "moment": "2.24.0"
},

现在 package.json 应该是这样的

"dependencies": {
    "chart.js": "2.9.3",
    "moment": "2.24.0",
    "moment-timezone": "^0.5.28",
    "react-chartjs-2": "2.9.0",
},
"resolutions": {
    "moment": "2.24.0"
},

请注意,我并未在此处包含所有包。

3) 删除整个node_modules文件夹和.lock文件(yarn.lock或package-lock.json)

4) 运行 yarn installnpm install

这对我有用。