[英]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.