[英]Chart Duplicates because of useEffect re-render
我有一個父組件,用於將道具(即backgroundColor
)傳遞給子組件( <LivePortfolioGraph />
)。
在我的子組件中,我有一個依賴數組,每次從父組件(即props.backgroundColor
)更改顏色時都會重新渲染。
現在我不想在每個渲染上創建一個新圖表,如果圖表存在,只需應用顏色選項。
非常感謝任何幫助。 謝謝。
父組件
const Main = (props) => {
const [backgroundColor, setbackgroundColor] = useState('#141d27');
const g = useRef(null);
return (
<div ref={g} className="FinancialChartIntro" >
<LivePortfolioGraph g={g} backgroundColor={backgroundColor} />
</div>
)
}
子組件
const LivePortfolioGraph = (props) => {
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(0);
useEffect( ()=> {
const handleStyle = _debounce(() => { chart.applyOptions({layout: {backgroundColor:props.backgroundColor } }); }, 100)
window.addEventListener("input", handleStyle);
const chart = createChart(props.g.current, options );
// Clean Up
return () => {
window.removeEventListener('input', handleStyle);
}
}, [props.backgroundColor])
更新我找到了一種刪除子節點(圖表副本)的黑客方法。 它會像瘋了一樣減慢頁面速度,我什至不想使用它。 仍在嘗試尋找另一種解決方案。
> if(props.g.current.childNodes.length > 2) { > props.g.current.removeChild(props.g.current.childNodes[2]) }
我認為您的問題是單個useEffect
掛鈎正在做“太多”的工作。 將chart
值移動到 React ref 並使用效果掛鈎來更新顏色/樣式。
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]);
只需執行檢查以查看圖表是否已被實例化。
這是我為設置圖表而創建的一個鈎子片段useSetupChart
useEffect(() => {
if (!chartContainerRef.current || chart) return;
setChart(createChart(chartContainerRef.current));
}, [chartContainerRef.current, chart]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.