Cannot read properties of undefined with react-chartjs-2 and chart js问题

Cannot read properties of undefined with react-chartjs-2 and chart js problem

当我想使用 react chartjs 时,它给我这些错误

我用于 chart.js 的版本是 ^3.5.0^4.0.1 for react-chartjs- 2

我将它降级到版本 2,但没有用

图表组件代码

import React from 'react'
import { Bar } from 'react-chartjs-2'
import { Chart as ChartJS } from 'chart.js/auto'

function Chart({ chartData }) {
    return <Bar data={chartData} />
}

export default Chart

主要成分

const [data, setData] = useState({
        labels: UserData.map((data) => data.year),
        datasets: [
            {
                label: 'Users Gained',
                data: UserData.map((data) => data.userGain),
            },
        ],
    })
<Chart chartData={data} />

数据

export const UserData = [
    {
        id: 1,
        year: 2016,
        userGain: 80000,
        userLost: 823,
    },
    {
        id: 2,
        year: 2017,
        userGain: 45677,
        userLost: 345,
    },
    {
        id: 3,
        year: 2018,
        userGain: 78888,
        userLost: 555,
    },
    {
        id: 4,
        year: 2019,
        userGain: 90000,
        userLost: 4555,
    },
    {
        id: 5,
        year: 2020,
        userGain: 4300,
        userLost: 234,
    },
]

问题可能与您import/read UserData 的方式有关。假设数据在 UserData.js 中定义,您可以按如下方式导入它:

import { UserData } from './UserData.js';

请看看这个 StackBlitz 看看它如何与您的代码一起工作。

主要成分:

import { UserData } from './UserData.js';
import React from 'react'

const [data, setData] = React.useState({
        labels: UserData?.map((data) => data.year),
        datasets: [
            {
                label: 'Users Gained',
                data: UserData?.map((data) => data.userGain),
            },
        ],
    })
<Chart chartData={data} />