React ApexCharts Donut环形图刷新/窗口Resize后消失问题求助
解决React ApexCharts环形图刷新/窗口调整后消失的问题
问题原因分析
- 初始状态类型不匹配:你把
ageGroupCounts的初始值设为字符串数组ageGroups,但ApexCharts的series要求数字类型数组,类型不匹配会导致图表重渲染时失效。 - 缺少加载状态处理:数据未返回时就渲染图表,易引发渲染异常;窗口调整触发响应式重绘时,错误的初始数据会导致图表无法重新渲染。
- useEffect依赖不完整:
fetchAgeGenderData的执行依赖api实例,但未将其加入useEffect依赖数组,可能导致数据更新逻辑失效。 - 固定宽度限制:图表设置固定
width='400',窗口调整时无法正确适配,引发渲染问题。
解决方案及修改代码
import React, { useState, useEffect } from 'react' import { Col } from 'antd' import Chart from 'react-apexcharts' import { endpoints, useApi } from 'src/api.context' export const AgeDonut = () => { const ageGroups = ['<18', '18-25', '26-49', '50-69', '70+'] // 修正初始状态为数字数组,匹配series要求的类型 const [ageGroupCounts, setAgeGroupCounts] = useState([]) // 添加加载状态,避免数据未就绪时渲染异常 const [isLoading, setIsLoading] = useState(true) const api = useApi() useEffect(() => { fetchAgeGenderData() // 加入api作为依赖,确保api实例变化时重新请求 }, [api]) const fetchAgeGenderData = () => { const params = { age_groups: ageGroups, } api.get(endpoints.PATIENT_STATS, params).then( (response) => { const data = response.data // 确保返回的是数字数组,避免非数组数据导致渲染失败 setAgeGroupCounts(Array.isArray(data.age_stats[1]) ? data.age_stats[1] : []) setIsLoading(false) }, (error) => { // 添加错误处理,设置默认数据防止图表崩溃 console.error('获取年龄统计数据失败:', error) setAgeGroupCounts([0, 0, 0, 0, 0]) setIsLoading(false) } ) } const options = { title: { text: 'Age', align: 'left', }, labels: ageGroups, responsive: [ { breakpoint: 480, options: { chart: { width: '100%', // 响应式宽度,适配父容器 }, legend: { position: 'bottom', }, }, }, ], } // 加载状态下显示占位符,避免空图表 if (isLoading) { return <Col>加载中...</Col> } return ( <Col style={{ width: '100%', maxWidth: 400 }}> <Chart options={options} series={ageGroupCounts} type='donut' width='100%' // 使用百分比宽度,适配父容器及窗口变化 /> </Col> ) }
关键修改点说明
- 修正初始状态类型:将
ageGroupCounts初始值改为空数组,确保和接口返回的数字数组类型一致。 - 添加加载状态:通过
isLoading控制图表渲染时机,避免数据未就绪时的异常渲染。 - 完善依赖与错误处理:将
api加入useEffect依赖,确保请求逻辑稳定;添加错误回调,设置默认数据防止图表崩溃。 - 响应式宽度调整:把图表宽度设为
100%,通过父容器Col控制最大宽度,适配窗口变化。
内容的提问来源于stack exchange,提问作者Danniel Little
相关产品推荐
相关产品推荐

