使用 react-google-charts 传递数组时,n.getFullYear 不是函数错误

IT技术 arrays reactjs charts google-visualization
2021-05-20 12:49:22

我正在尝试在 react-google-chart 日历图表中查看日期数据。我有一系列习惯,每个习惯都有一系列完成天数。我试图将这些完成日映射到 Chart 组件,但在 DOM 上出现错误n.getFullYear is not a function问题可能是我不知道如何以正确的方式将数据传递给 Chart 组件,从数组映射。我该怎么做?

这是我的代码:

//example of dateObj:
habit.completions[0] = { thisYear: 2020, thisDay: 3, thisMonth: 2 }
import React from 'react';
import Chart from 'react-google-charts';

const Habit = ({ habit, handleRemove }) => {
  if (!habit) {
    return null;
  }


  const completionDays = habit.completions.map(dateObj => {
    return [new Date(dateObj.thisYear, dateObj.thisDay, dateObj.thisMonth), 1]
  })

  const dataNotWork = [
    [
      { type: 'date', id: 'Date' },
      { type: 'number', id: 'Completions'}
    ],
    completionDays
  ]

  const dataThatWorks = [
    [{ type: 'date', id: 'Date' }, { type: 'number', id: 'Completions' }],
    [new Date(2012, 3, 13), 1],
    [new Date(2012, 3, 14), 1],
    [new Date(2012, 3, 15), 1],
    [new Date(2013, 2, 10), 1]
  ]

  console.log('completionDays', completionDays)

  return (
    <div>
      <Chart
        width={750}
        height={350}
        chartType="Calendar"
        loader={<div>Loading Chart</div>}
        data={dataNotWork}
        options={{
          title: habit.name
        }}
        rootProps={{ 'data-testid': '1' }}
      />
      <div>
        <button onClick={() => handleRemove(habit)}>Delete</button>
      </div>
    </div>
  );
};

export default Habit 

这是返回前的完成天数的 console.log

completionDays 
(2) [Array(2), Array(2)]
0: (2) [Wed Apr 01 2020 00:00:00 GMT+0300 (Eastern European Summer Time), 1]
1: (2) [Wed Apr 01 2020 00:00:00 GMT+0300 (Eastern European Summer Time), 1]
length: 2
__proto__: Array(0)

1个回答

映射看起来不错,
我相信这是您将行添加到此处的数据定义的地方...

const dataNotWork = [
  [
    { type: 'date', id: 'Date' },
    { type: 'number', id: 'Completions'}
  ],
  completionDays
]

问题是completionDays一个数组数组。

所以而不是通过...

[new Date(2012, 3, 13), 1],
[new Date(2012, 3, 14), 1],
[new Date(2012, 3, 15), 1],
[new Date(2013, 2, 10), 1]

你路过...

[
  [new Date(2012, 3, 13), 1],
  [new Date(2012, 3, 14), 1],
  [new Date(2012, 3, 15), 1],
  [new Date(2013, 2, 10), 1]
]

所以它试图从数组定义中获取日期--> []

相反,连接两个数组...

var data = [
  [
    { type: 'date', id: 'Date' },
    { type: 'number', id: 'Completions'}
  ],
];

data = data.concat(completionDays);