问题描述:echarts饼图,按以下方式通过setOption()方法更新数据时候,看到图表闪烁了一下,然后又变回了初始状态
const newData = [
{ value: a, name: '变量a',itemStyle: { color: aColor } },
{ value: b, name: '变量b',itemStyle: { color: bColor} },
]
if (echartsRef.current) {
let newOption = option
newOption.legend.formatter = updateLegendFormatter(newData)
newOption.series[0].data = newData
setOption(newOption)
const chartInstance = echartsRef.current.getEchartsInstance();
chartInstance.setOption(newOption);
}
//updateLegendFormatter方法
const updateLegendFormatter = (data) => {
return function (name) {
let target = data.find(item => item.name === name);
return target ? `{a|${name}}\n\n{b|${target.value.toString()}}{c|个}` : '';
};
};
option的初始状态是通过const直接定义的
解决过程:通过useState的方式定义option,并在数据更新时定义一个临时的option等于旧option,直接更新最新option,并在更新时将整个option更新,问题解决,以下代码
const [option,setOption] = useState({
//初始option
})
const newData = [
{ value: a, name: '变量a',itemStyle: { color: aColor } },
{ value: b, name: '变量b',itemStyle: { color: bColor} },
]
if (echartsRef.current) {
let newOption = option
newOption.legend.formatter = updateLegendFormatter(newData)
newOption.series[0].data = newData
setOption(newOption)
const chartInstance = echartsRef.current.getEchartsInstance();
chartInstance.setOption(newOption);
}
html结构
<ReactECharts
ref={echartsRef}
option={option}
style={{ height: '200px', width: '400px',marginTop:'20px' }}
echarts={echarts}
/>
问题原因目前仍未知