1

我有一个父组件,用于将道具(即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])

第一次渲染

当我改变颜色时,另一个图表显示了以前的 defaultValue

创建的元素

更新 我找到了一种删除子节点(图表副本)的黑客方法。它会像疯了一样减慢页面速度,我什至不想使用它。仍在尝试寻找另一种解决方案。

> if(props.g.current.childNodes.length > 2) {
> props.g.current.removeChild(props.g.current.childNodes[2])  }
4

2 回答 2

1

我认为您的问题是单个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]);
于 2021-04-28T04:48:26.653 回答
1

只需执行检查以查看图表是否已被实例化。

这是我为设置图表而创建的钩子片段useSetupChart

  useEffect(() => {
    if (!chartContainerRef.current || chart) return;

    setChart(createChart(chartContainerRef.current));
  }, [chartContainerRef.current, chart]);

于 2021-12-28T16:13:47.037 回答