reactjs React图2:无法读取未定义的属性(阅读'map')

cx6n0qe3  于 2023-03-01  发布在  React
关注(0)|答案(5)|浏览(162)

我尝试在项目中使用react-chartjs-2创建图表,但遇到以下错误:

TypeError: Cannot read properties of undefined (reading 'map')
setDatasets
C:/Users/vivek/code/src/utils.ts:46
  43 |   currentData: ChartData<TType, TData, TLabel>,
  44 |   nextDatasets: ChartDataset<TType, TData>[]
  45 | ) {
> 46 |   currentData.datasets = nextDatasets.map(nextDataset => {
  47 |     // given the new set, find it's current match
  48 |     const currentDataset = currentData.datasets.find(
  49 |       dataset =>

这是我的代码:

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

const BarChart = () => {
  return (
    <div>
      <Bar
        data={{
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        }}
        width={600}
        height={400}
        options={{ maintainAspectRatio: false }}
      />
    </div>
  );
};
export default BarChart;

我正在尝试创建条形图

6pp0gazn

6pp0gazn1#

也许这对某人会有帮助?
我遇到了完全相同的错误以上,我的版本如下:
"图表. js":"^3.6.2","React":"^17.0.2","React图表-2":"^4.0.0",
这里的关键实际上是文档,[https://react-chartjs-2.netlify.app/docs/migration-to-v4][1]具体来说,在我的案例中,大约在页面的中间部分是"v4-Line组件"部分。
下面是一个代码的例子,我得到的工作后,审查上述文档,(和撞墙我的头几个小时!!)。

import React, { useState, useEffect }  from "react";
import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';
import { Chart as ChartJS, LineController, LineElement, PointElement, LinearScale, Title } from 'chart.js';

ChartJS.register(LineController, LineElement, PointElement, LinearScale, Title);

function Graph() {    
    useEffect(() => {
        const fetchSamplings = async () => {
            const res = await fetch("http://192.168.1.100:8080/consumer/v1/sampling/sensor/esp_planter_1/humidity/interval/24")
            const data = await res.json();
            
            setChartData({
                labels: data.map((sampling) => sampling.samplingDate),
                datasets: [{
                    label: "Humidity",
                    data: data.map((sampling) => sampling.humidity)                    
                }]
            });
        }
        fetchSamplings();        
    }, [])

    const [chartData, setChartData] = useState({
        datasets: [],
    });

    return(
        <div style={{height: "1024px", width: "2048px"}}>
            <Chart type='line' data={chartData} />
        </div>
    )
}

export default Graph;

注意,从获取返回的json看起来像:

[
    {
        samplingDate: "2021-12-22T02:50:35.393+00:00",
        sensor: "esp_planter_1",
        humidity: 51.5
    },
    {
        samplingDate: "2021-12-22T02:49:34.874+00:00",
        sensor: "esp_planter_1",
        humidity: 53.2
    },
    {
        samplingDate: "2021-12-22T02:48:34.867+00:00",
        sensor: "esp_planter_1",
        humidity: 52.4
    }
]

Hope this helpful!!

  [1]: https://react-chartjs-2.netlify.app/docs/migration-to-v4
kognpnkq

kognpnkq2#

您在提供数据时出错。请检查文档并遵循结构。以下是来自文档visit here的示例

const labels = Utils.months({count: 7});
const data = {
  labels: labels,
  datasets: [{
    label: 'My First Dataset',
    data: [65, 59, 80, 81, 56, 55, 40],
    backgroundColor: [
      'rgba(255, 99, 132, 0.2)',
      'rgba(255, 159, 64, 0.2)',
      'rgba(255, 205, 86, 0.2)',
      'rgba(75, 192, 192, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(153, 102, 255, 0.2)',
      'rgba(201, 203, 207, 0.2)'
    ],
    borderColor: [
      'rgb(255, 99, 132)',
      'rgb(255, 159, 64)',
      'rgb(255, 205, 86)',
      'rgb(75, 192, 192)',
      'rgb(54, 162, 235)',
      'rgb(153, 102, 255)',
      'rgb(201, 203, 207)'
    ],
    borderWidth: 1
  }]
};
bvjxkvbb

bvjxkvbb3#

import {Chart as ChartJS} from 'chart.js/auto'

至关重要,这解决了我的问题

yvgpqqbh

yvgpqqbh4#

import { useEffect, useState } from "react";
**import "chart.js/auto";
import { Line } from "react-chartjs-2";**

const WeekMonthWeather = (props) => {
  const { latitude, longitude } = props;
  const [chartData, setChartData] = **useState({ datasets: [] });**

  const fetchData = async () => {
    try {
      const response = await fetch(
        `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&hourly=temperature_2m`
      );
      const data = await response.json();
      if (data && data.hourly) {
        // check if data.hourly is defined
        console.log(data);
        const temperatures = data.hourly.temperature_2m;
        console.log(temperatures);
        const labels = data.hourly.time;
        console.log(labels);
        setChartData({
          labels: labels,
          datasets: [
            {
              label: "Temperature",
              data: temperatures,
              backgroundColor: "rgba(75,192,192,0.2)",
              borderColor: "rgba(75,192,192,1)",
              borderWidth: 1,
            },
          ],
        });
      }
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    fetchData();
  }, [latitude, longitude]);
 return (
    <div style={{ height: "512px", width: "1024px" }}>
      <h2>Weather Chart</h2>
      <Line data={chartData} />
    </div>
  );
};

export default WeekMonthWeather;

我是React的新手,这种方法对我很有效。
1.导入"chart.js/auto"文件;
1.从"react-chartjs-2"导入{Line};
1.常量[图表数据,设置图表数据]=**使用状态({数据集:[]});

ioekq8ef

ioekq8ef5#

我遇到了同样的问题。我的组件看起来像这样:

<Doughnut
  datasetIdKey='id'
  data={setChartData}
  options={options}
/>

在我改变之后

data={chartData}

那个错误就消失了。

相关问题