将 Chart JS 与 React 结合使用时,我收到一条错误消息,指出它无法映射我的数据集中的某些内容。控制台日志中的一切看起来都很好,但我似乎无法弄清楚发生了什么。当我不使用状态时,这之前是有效的。我现在正在使用状态,因为我想从 fetch API 加载数据。下面是我的代码。下面还有完整的错误消息。
非常感谢任何帮助:
import React, {useEffect, useState} from 'react';
import { Bar} from 'react-chartjs-2';
const Chart = (props) => {
const [data, setData] = useState({})
const [options, setOptions] = useState({})
useEffect(()=>{
prepareData()
},[])
const prepareData = ()=>{
const labels = ["1","2","3"]
const barData = [50,30,20]
const lineData = [50,80,100]
let d = {
labels: labels,
datasets: [
{
label: 'Total Quantity',
data: barData,
backgroundColor: "rgba(0,100,200,0.25)",
order: 0,
},
{
label: 'Running Pct of Total',
data: lineData,
borderColor: "rgb(200,200,200)",
backgroundColor: "rgb(200,200,200)",
type: 'line',
order: 1,
pointStyle: 'circle',
pointRadius: 4,
}
]}
setData(d)
prepareOptions()
}
const prepareOptions = ()=>{
let o = {
scales: {
x: {
type: 'category',
position: 'bottom',
grid:{
display: false
}
},
y: {
beginAtZero: true,
grid:{
display: false
},
display: false
},
},
plugins:{
title: {
display: true,
color: 'black',
font: {
size: 16,
},
},
datalabels:{
display: true
}
}
}
setOptions(o)
}
return (
<div className="container">
<Bar data={data} options={options} />
</div>
);
};
export default Chart;
Full error message:
utils.ts:57 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
at setDatasets (utils.ts:57:1)
at cloneData (utils.ts:94:1)
at renderChart (chart.tsx:43:1)
at chart.tsx:97:1
at commitHookEffectListMount (react-dom.development.js:23150:1)
at commitPassiveMountOnFiber (react-dom.development.js:24926:1)
at commitPassiveMountEffects_complete (react-dom.development.js:24891:1)
at commitPassiveMountEffects_begin (react-dom.development.js:24878:1)
at commitPassiveMountEffects (react-dom.development.js:24866:1)
at flushPassiveEffectsImpl (react-dom.development.js:27039:1)
状态的初始值为空对象,这就是为什么
chart-js
不能在其上使用map
。这是我的建议:
const [data, setData] = useState()
const [options, setOptions] = useState()
return (
{data && options &&
<div className="container">
<Bar data={data} options={options} />
</div>
}
);