簡體   English   中英

ReactJS-子組件不會卸載

[英]ReactJS—Child Component does not unmount

我創建了一個包裝器組件,可以將其與另一個組件一起配置,以共享某些功能。 基本上,包裝器Component創建一個新的DomNode並從其props渲染子組件,如下所示:

//wrapper
componentDidMount () {
  this.node = document.body.appendChild(document.createElement('div'));
}

componentDidUpdate () {
  if (this.state.editing) {
    ReactDOM.render(this.props.component, this.node);
  } else {
    ReactDOM.unmountComponentAtNode(this.node)
  }
}

//component from within the props of the wrapper above
componentWillUnmount () { /* runs */ }

render () {
  return (
    <div>
      <AnotherThing />
    </div>
  );
}

但是 <AnotherThing />實例的componentWillUnmount()永遠不會觸發。 這是默認值嗎,還是我在這里錯了? 我希望為子樹中的所有組件觸發componentWillUnmount()

UPDATE

一切都按預期進行。 我的觀看過程停止了工作,這就是為什么我看不到正在卸載的原因。

您可以比現在更輕松地實現所需的目標。

您的渲染函數可能如下所示:

render () {
  return (
    <div>
      { this.state.editing ? this.props.component : null }
    </div>
  )
}

render將在您的狀態或道具發生變化時運行,因此您不需要單獨的生命周期方法即可實現想要實現的目標。 React將負責安裝和卸載this.props.component

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM