Recharts图表因无关状态变更重绘后空白问题求助
解决Recharts柱状图重绘后空白的问题
- 核心问题是ResponsiveContainer和BarChart的尺寸设置冲突,加上父容器可能无明确尺寸,导致重绘时图表尺寸计算异常。
具体修复步骤:
- 删掉BarChart组件上的
width和height属性,ResponsiveContainer已经负责自适应尺寸,重复设置会打乱尺寸计算逻辑。 - 给ResponsiveContainer的父容器设置明确的宽高(比如固定高度300px、宽度100%),确保100%的尺寸有参考基准,避免重绘后容器塌陷。
- 可选:给ResponsiveContainer添加
minWidth/minHeight,防止极端情况下容器尺寸变为0。
修改后的代码示例:
// 给父容器设置明确尺寸 <div style={{ width: '100%', height: 300 }}> <ResponsiveContainer width="100%" height="100%"> <BarChart data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="country" /> <YAxis /> <Tooltip itemStyle={{ color: '#000000' }} /> <Legend /> <Bar dataKey="value" fill="#8884d8" /> </BarChart> </ResponsiveContainer> </div>
额外说明:
如果问题仍存在,可尝试用useMemo缓存data,避免组件重绘时不必要的数据重新计算,但这个场景下主要问题还是尺寸冲突。
内容的提问来源于stack exchange,提问作者Vedant Shah
相关产品推荐
相关产品推荐

