![](/img/trans.png)
[英]Uncaught TypeError: Cannot read properties of undefined (reading 'map')
[英]Error: Uncaught TypeError: Cannot read properties of undefined (reading 'map')
代码中有什么问题? 我似乎无法得到它。 错误显示:
utils.ts:53 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
and
react-dom.development.js:18687 The above error occurred in the <ForwardRef(ChartComponent)> component
我附上了代码。 每当我运行代码时,屏幕就会变成空白和白色。 删除 <Line../> 片段后,应用程序运行良好,因此错误似乎在该特定部分。 但我似乎无法理解错误是什么。
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
我查看了react-chartjs-2源代码,似乎根Chart组件的 props 中存在错误。
您需要将datasets
字段添加到您作为data
属性传递的 object 中。 它应该是一个数组,稍后将由库的内部函数之一映射。 (可能这就是错误的来源)
像文档一样:
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],
}]
};
在 return() 之前只需添加
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.