0

我有一个父组件和子组件。子组件将根据条件通过父组件呈现。因此,当孩子被渲染时,所有 useEffect 和其他代码都被执行,我能够实现 componentDidMount 类型的方法。我不是直接访问子组件,而是仅使用 Parent 根据父级的道具来渲染它。一旦我的子组件可见,我就会调用一个方法来重置“doesChildExists”道具并重新渲染 ParentComponent,并且由于条件失败,因此不会渲染(卸载)ChildComponent。有一次,ChildComponent 即将卸载,我需要做一些事情,但现有的 useEffect 似乎没有被调用。我该如何处理?请帮忙!!

请让我知道这是否不是正确的方法,我已经以不同的方式处理孩子的渲染。

const ChildComponent: FunctionComponent<Props> = (props: Props) => {
    useEffect(() => {
       return () => {
            // handle unmount
       }
    }, []);
    return (
        <div class='textDiv'> 
           This is content
        </div>
    )

}

const ParentComponent: FunctionComponent<ParentProps> = (props: ParentProps) => {
      return (
          <>
               {doesChildExists &&
        createPortal(<ChildComponent />, document.body)}
          </>
      )
}

4

0 回答 0