javascript - 错误 : Uncaught TypeError: Cannot read properties of undefined (reading 'map' )

标签 javascript reactjs react-native

代码中有什么问题?我似乎无法得到它。 错误显示:

utils.ts:53 Uncaught TypeError: Cannot read properties of undefined (reading 'map')

react-dom.development.js:18687 The above error occurred in the <ForwardRef(ChartComponent)> component

我附上了代码。每当我运行代码时,屏幕都会变成空白。 删除 片段后,应用程序运行正常,因此错误似乎出现在该特定部分。但我似乎无法理解错误是什么。

import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { CryptoState } from '../CryptoContext';
import { HistoricalChart } from '../config/api';
import { createTheme } from '@material-ui/core/styles';
import { CircularProgress, makeStyles, ThemeProvider } from '@material-ui/core';
import { Line } from 'react-chartjs-2';



const useStyles = makeStyles((theme) => ({
  container:{
    width: "75%",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    marginTop: 25,
    padding: 40,
    [theme.breakpoints.down("md")]:{
      width: "100%",
      marginTop: 0,
      padding: 20,
      paddingTop: 0,
    },
  },
}));

const CoinInfo = ({ coin }) => {

  const [historicalData, setHistoricalData] = useState();
  const [days, setDays] = useState(1);

  const { currency } = CryptoState();

  const fetchHistoricalData = async () => {
    const { data } = await axios.get(HistoricalChart(coin.id,days,currency)) 

    setHistoricalData(data.prices);
  };

  useEffect(() => {
    fetchHistoricalData();
  }, [currency, days]);

  const darkTheme = createTheme({
    palette: {
      primary : {
        main: "#fff",
      },
      type: "dark",
    }
  });
  
  const classes = useStyles();

  //console.log("data",historicalData);

  return (
    <ThemeProvider theme={darkTheme}>
      <div className = {classes.container}>        
        {!historicalData ? (
          <CircularProgress
            style={{ color: "#40E0D0" }}
            size={250}
            thickness={1}
          />
        ): (
          <>
            <Line
              data={{
                labels: historicalData && historicalData.map((coin) => {
                  let date = new Date(coin[0]);
                  let time = 
                          date.getHours() > 12
                            ? `${date.getHours() - 12}:${date.getMinutes()} PM`
                            : `${date.getHours()}:${date.getMinutes()} AM`;
                  return days===1?time: date.toLocaleDateString();
                })
              }}
            />
          </>
        )}

      </div>
    </ThemeProvider>
  )
}

export default CoinInfo

console.log("data", HistoricalData) 的输出: Output

最佳答案

我查看了 react-chartjs-2 源代码,根 Chart 组件的 props 似乎有一个错误。

您需要将 datasets 字段添加到作为 data 属性传递的对象。它应该是一个数组,稍后将被库的内部函数之一映射。 (可能这就是错误的来源)

喜欢文档:

 const data = {
labels: labels,
datasets: [{
  label: 'My First dataset',
  backgroundColor: 'rgb(255, 99, 132)',
  borderColor: 'rgb(255, 99, 132)',
  data: [0, 10, 5, 2, 20, 30, 45],
}]
};

关于javascript - 错误 : Uncaught TypeError: Cannot read properties of undefined (reading 'map' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73304964/

相关文章:

javascript - 更改 CSS3 动画的开始

javascript - 在 Protractor 中遍历 map 函数

javascript - React - 模块解析失败 : Unexpected Token. 您可能需要适当的加载程序来处理此文件类型

javascript - 使用自定义 React Hook 提交包含数据的表单

javascript - react native : How to fix error with Button component during onPress?

javascript - 我的 Firestore 中有超过 50,000 个文档,排序和查找的时间超过 30 秒,限制为 50 个。如何加快速度?

php - jquery 类型错误 : Response is null

VS.Net 的 Javascript 自动完成插件

javascript - 使用组件变量来 react Native Promises 和 componentDidMount 行为

react-native - 在 react-native 上打印到蓝牙打印机