Anychart Lib在每个渲染上复制一个组件



这是我的第一篇文章,我在组件构建中使用了带有React的Anychart库,我能够实现,但在每次渲染图表时,Anychart修复使用的方式是重复的。这是我的组件

const Chart: React.FunctionComponent = () => {
function charts()  {
// create data
const data = [
{
x: '2022-07-26',
y: '0.29822798232939185',
},
];
// create a chart and set the data
const chart = anychart.line();
chart.data(data);
// set the chart title
chart.title('Sales of the Most Popular Products of ACME Corp.');
// set the titles of the axes
chart.xAxis().title('Year');
chart.yAxis().title('Revenue');
// draw
chart.container('container');
chart.draw();
}
React.useEffect(() => {
charts();
}, []);
return <StyledDiv id="container" />;
};
export default Chart;

正如你所看到的,这很简单,但每次应用程序进行渲染时,这个组件都会被复制并生成一个新的图表。

这个问题可以通过在charts((函数中返回图表本身来解决。

function charts()  {
//your code here 
// draw
chart.container('container');
chart.draw();
//returning chart variable
return chart
}

然后必须在useEffect钩子中返回chart.dispose((函数。

useEffect(() => {
const chart = charts();
// Return a cleanup function to remove the chart when the component unmounts
return () => chart.dispose();
}, []);

这个问题是由于React LifeCycle引起的,可以通过在渲染后删除重复项来解决,这就是dispose函数的作用。您可以使用dispose函数的例子,它可以防止React中的重复。

最新更新