reactjs Chart.js此方法未实现:检查是否提供了完整的日期适配器,包含chartjs-adapter-date-fns时出错

u2nhd7ah  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(139)

Chart.js时间线图不会呈现,而是在x轴设置为type: time时抛出错误,如in all the docs所示,请注意,我在chart.js周围使用4.1.2和react-chartjs-2 Package

import React from 'react';

import 'chartjs-adapter-date-fns';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  TimeScale,
} from 'chart.js';

import { Line } from 'react-chartjs-2';

ChartJS.register(LinearScale, PointElement, LineElement, Title, Tooltip, Legend, TimeScale, CategoryScale);

export const Test = () => {
  const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
  const options = {
    scales: {
      x: {
        type: 'time',
      },
    },
  };
  const dataset = {
    labels,
    datasets: [
      {
        label: 'Dataset 1',
        data: labels.map(() => Math.floor(Math.random() * 1000)),
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgba(255, 99, 132, 0.5)',
      },
      {
        label: 'Dataset 2',
        data: labels.map(() => Math.floor(Math.random() * 1000)),
        borderColor: 'rgb(53, 162, 235)',
        backgroundColor: 'rgba(53, 162, 235, 0.5)',
      },
    ],
  };
  return <Line options={options} data={dataset} />;
};

但是,当选项更改为以下内容时,它会 * 渲染:

const options = {
    responsive: true,
    adapters: {
      type: 'time',
    },
  }

我在文档中找不到任何地方说要使用adapters.time选项。为什么这样做?我如何才能让它像文档中那样工作。

mtb9vblg

mtb9vblg1#

你知道你的项目是使用CommonJS(CJS)还是ECMAScript模块(ESM)吗?
我想知道你是否在使用Chart.js时遇到了双重包危险-它包含单独的CJS和ESM版本,并且它有全局状态(它的日期/时间适配器注册表),并且这个注册表似乎没有在CJS和ESM版本之间共享。
因此,如果您的项目使用的是Chart.js的CJS版本,而您使用的适配器使用的是Chart.js的ESM版本(反之亦然),则无法正常工作。
chartjs-adapter-date-fns似乎使用ESM版本。(参见here。)
This similar question似乎是相关的(尽管它没有一个确定的答案,所以我不确定这是怎么回事),

相关问题