由于 useEffect 重新渲染而导致图表重复 [英] Chart Duplicates because of useEffect re-render
问题描述
我有一个父组件,我用它来将道具(即 backgroundColor
)传递给子组件(<LivePortfolioGraph/>
).
I have a parent component which I'm using to pass props (i.e backgroundColor
) to child component( <LivePortfolioGraph />
).
在我的子组件中,我有一个依赖数组,每次从父组件更改颜色时都会重新渲染,即 (props.backgroundColor
).
In my child component I have a dependency array that re-renders every time color is changed from parent i.e (props.backgroundColor
).
现在我不想在每次渲染时都创建一个新图表,如果图表存在,只需应用颜色选项.
Now i don't want want to create a new graph on every render, if chart exist just apply color options.
非常感谢您的帮助!谢谢.
Really appreciate any help! Thanks.
父组件
const Main = (props) => {
const [backgroundColor, setbackgroundColor] = useState('#141d27');
const g = useRef(null);
return (
<div ref={g} className="FinancialChartIntro" >
<LivePortfolioGraph g={g} backgroundColor={backgroundColor} />
</div>
)
}
)}
子组件
更新我找到了一种删除子节点(图表重复)的hacky方法.它像疯了一样减慢了页面的速度,我什至不想使用它.仍在尝试寻找其他解决方案.
> if(props.g.current.childNodes.length > 2) {
> props.g.current.removeChild(props.g.current.childNodes[2]) }
推荐答案
我认为您的问题是单个 useEffect
钩子做得太多"了工作.将 chart
值移动到 React ref 中并使用效果钩子更新颜色/样式.
I think your issue is the single useEffect
hook is doing "too much" work. Move the chart
value into a React ref and use the effect hook to update the color/styling.
const LivePortfolioGraph = (props) => {
const [width, setWidth] = React.useState(0);
const [height, setHeight] = React.useState(0);
const chart = React.useRef(createChart(props.g.current, options);
React.useEffect(()=> {
const handleStyle = _debounce(() => {
chart.current.applyOptions({
layout: {
backgroundColor: props.backgroundColor,
},
});
}, 100);
window.addEventListener("input", handleStyle);
// Clean Up
return () => {
window.removeEventListener('input', handleStyle);
}
}, [props.backgroundColor]);
这篇关于由于 useEffect 重新渲染而导致图表重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!