使用react-chartjs-2同时渲染多图表时Doughnut图表报错求助
问题:Bar图表正常渲染,但Doughnut图表报错无法显示
我已成功渲染Bar图表且无报错,但启用Doughnut图表组件时,控制台出现如下错误:
react-dom.development.js:22831 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:23139:1) at commitPassiveMountOnFiber (react-dom.development.js:24917:1) at commitPassiveMountEffects_complete (react-dom.development.js:24880:1) at commitPassiveMountEffects_begin (react-dom.development.js:24869:1) at commitPassiveMountEffects (react-dom.development.js:24856:1) at flushPassiveEffectsImpl (react-dom.development.js:27029:1)
我推测问题可能是缺少Chart.js中Doughnut图表的相关注册,以下是我的代码:
相关代码
app.js
import { Chart as ChartJs, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, } from 'chart.js' import { Bar, Doughnut } from 'react-chartjs-2'; import {useState, useEffect} from 'react' import { individual_dataset } from './data'; import { Container, NavBar, ConfidenceContainer, OutLine, DesigInput, Box, Option, ChartsContainer, } from './style' ChartJs.register( CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, ) function App() { const [confidenceData, setConfidenceData] = useState({ datasets: [] }) const [ chartOptions, setChartOptions] = useState({}); const [gaughData, setGaughData] = useState({ dataset:[] }) const [gaughChartOptions, setGaughChartOptions] = useState({}) const [selected, setSelected] = useState({}); const [showList, setShowList] = useState(false); const handleItemChange=(item)=>{ setSelected(item) setShowList(false) } useEffect(()=>{ if(selected?.name){ setConfidenceData({ labels: ['confidence', 'active listening', 'total'], datasets: [ { label: 'Average', data: [58.05, 67.125, 125.5], borderColor: "rgb(53,162, 235)", backgroundColor: "#9EA1D4" }, { label: 'Individual Score', data: [selected.total_score_confidence, selected.total_score_active_listening, selected.total_score_overall], borderColor: "rgb(53,162, 235)", backgroundColor: "#FD8A8A" }, ] }) setGaughData({ labels:['Confidence', 'left over', 'hi'], datasets: [{ label: 'My First Dataset', data: [300, 50, 100], backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(54, 162, 235)', 'rgb(255, 205, 86)' ], hoverOffset: 4 }], }) } setGaughChartOptions({ }) setChartOptions({ responsive: true, plugins: { scales: { y:{ min: 200, max: 200, stepSize: 40, } }, legend:{ position: "bottom", labels:{ pointStyle: 'circle' } }, title:{ display: true, text: `Performance of ${selected?.name}`, } } }) },[selected]) return ( <Container> <NavBar> <h2> {selected?.name ? `${selected.name}\'s Performance` : "Individual Performance"}</h2> <OutLine> <DesigInput onClick={()=>setShowList(!showList)}>{selected?.name?selected.name: "Select Person"}</DesigInput> { showList && <Box> <Option onClick={()=>handleItemChange()}>NONE</Option> {individual_dataset.map((item)=>{ return <Option key={item.id} onClick={()=>handleItemChange(item)} >{item.name}</Option>; })} </Box>} </OutLine> </NavBar> <ChartsContainer> { selected?.name && <ConfidenceContainer key={'confidence'}><Bar key={'confidence'} options={chartOptions} data={confidenceData} /></ConfidenceContainer>} {selected?.name && <Doughnut options={gaughChartOptions} data={gaughData} />} </ChartsContainer> </Container> ); } export default App;
data.js
data = [ { id:"1", name:"Shivam", total_score_confidence:"100", total_score_active_listening:"100", total_score_overall:"200" }, { id:"2", name:"Utkarsh", total_score_confidence:"57", total_score_active_listening:"85", total_score_overall:"142" }, ]
我的需求是实现Bar图表与Doughnut图表同时渲染。
解决方案
问题根源
你推测的「缺少Doughnut图表相关注册」是原因之一,但还有一个更关键的错误:
- 未注册Doughnut图表依赖的
ArcElement组件(Chart.js中饼图/环形图必须使用该元素) - 初始化
gaughData时写错属性名:将datasets(复数)写成dataset(单数),导致Chart.js读取不到数据集,触发mapundefined报错
修复步骤
1. 注册Doughnut所需的Chart.js组件
在app.js的Chart.js导入中添加ArcElement,并完成注册:
import { Chart as ChartJs, CategoryScale, LinearScale, BarElement, ArcElement, // 新增 Title, Tooltip, Legend, } from 'chart.js' // 注册列表中添加ArcElement ChartJs.register( CategoryScale, LinearScale, BarElement, ArcElement, // 新增 Title, Tooltip, Legend, )
2. 修正gaughData的初始化属性名
将初始化时的dataset改为datasets(复数):
const [gaughData, setGaughData] = useState({ datasets: [] // 原先是dataset:[],改为datasets })
3. 可选:优化数据类型(避免字符串数值问题)
data.js中分数为字符串类型,Chart.js会自动转换,但建议统一转为数值类型避免潜在问题,在useEffect中处理选中项数据时修改:
data: [ Number(selected.total_score_confidence), Number(selected.total_score_active_listening), Number(selected.total_score_overall) ]
完成以上修改后,Bar和Doughnut图表即可同时正常渲染,控制台不再出现报错。
内容的提问来源于stack exchange,提问作者Saikiran Jetti
相关产品推荐
相关产品推荐

