簡體   English   中英

ReactJs如何知道何時從DOM中刪除組件

[英]ReactJs how to know when a component is removed from DOM

我目前正面臨React的問題。 我需要知道何時從DOM中刪除組件。

我在組件生命周期中找到的全部是componentWillUnmount,它在從DOM中刪除組件之前被調用。

有什么辦法可以用React做到這一點? 用簡單的javascript?

謝謝。

[編輯]

@jpdelatorre“普通javascript” ===不使用庫;-)

我的用例是在react組件中使用jsPlumb。

基本上jsPlumb是一個通過位置計算在DOM中繪制svg的庫。

在我的主要組件中,有一個項目列表。 每個項目都是一個組件。 在每個渲染項目上,我使用JsPlumb進行繪制。

但是...當我刪除列表中的一個項目時,這些項目在DOM中的位置發生了變化,因此我需要讓jsPlumb根據新的位置重繪內容。 所以這就是為什么我需要知道何時從DOM中完全刪除組件。

componentWillUnmount是正確的生命周期方法。 如您所說,它是在刪除組件之前觸發的。 如果您需要等待直到將其刪除,則可以使用setTimeout和較短的超時值來安排當前任務完成后的回調。

componentWillUnmount是可以掛鈎的生命周期方法。

但是如前所述,如果您想在component1中了解如何卸載component2,則需要在其生命周期方法中觸發component2中的操作,該操作應在component1中進行預訂,並在component1偵聽器中進行一些操作。

如前所述,您需要componentWillUnmount 這是React中的一個簡單示例(我在其中添加了一些注釋以獲取要執行的操作):

var Button = React.createClass({
  componentWillUnmount: function(){
      // console will show this message when compoent is being Unmounted("removed")
        console.log('Button removed');
  },

  render() {
    return <h1 ref='button_node'>
    <ReactBootstrap.Button bsStyle="success">Red</ReactBootstrap.Button>
    </h1>;
  }
});  



var RemoveButton = React.createClass({
  getInitialState: function() {
     // this state keep tracks if Button removed or not
     //(you can use it for some redrawing or anything else in your code)
     return {buttonMounted: true}
  },

  mountRedButton: function(){
    ReactDOM.render(<Button/>, document.getElementById('button'));
    this.setState({buttonMounted: true});
  },

  unmountRedButton: function(){
    ReactDOM.unmountComponentAtNode(document.getElementById('button'));
    this.setState({buttonMounted: false});
  },

  render() {
    return <h1>
      //based on condition if Button compoennt removed or not we show/hide different buttons
      { this.state.buttonMounted ? <ReactBootstrap.Button onClick={this.unmountRedButton } bsStyle="danger">Remove Red Button!</ReactBootstrap.Button> : null}
      { this.state.buttonMounted ? null :<ReactBootstrap.Button onClick={this.mountRedButton } bsStyle="success">Add Red Button!</ReactBootstrap.Button> }        
    </h1>;
  }
});


// mount components    
ReactDOM.render(<Button/>, document.getElementById('button'));
ReactDOM.render(<RemoveButton/>, document.getElementById('remove'));

這是有關JSFiddle的完整工作示例

關於“普通javascript”-您已經在使用React JS,我的示例基於React和ReactDom,僅此而已(實際上也有react-bootstrap,我只為漂亮的按鈕添加了它,根本不需要)

更新:使用MutationObserver怎么樣? 如果您需要刪除DOM中的Node卻在刪除節點之前觸發componentWillUnmount的時間(這對於您來說似乎無法解決),則可以使用它。 按照我的按鈕示例:

var removalWatcher = new MutationObserver(function (e) {
    var removalTimeStamp = '[' + Date.now() + '] ';
  if (e[0].removedNodes.length) {
    console.log('Node was removed', e[0].removedNodes, 'timestamp:', removalTimeStamp)
  };
});

這是帶有更新示例的JsFiddle 您可以比較打印在控制台中的MutationObserver和React ComponentWillUnmount時間戳。

好的,謝謝大家! 我找到了適合我的需求的解決方案,並且(恕我直言)干凈...

在我的父組件中,我處理componentDidUpdate生命周期事件,在那里,我可以知道(使用prevProps和props)是否進行了更改以觸發我的操作...

class MyComponent extends Component {
    // this one is called each time any props is changed
    componentDidUpdate(prevProps, prevState) {
       // if condition is matched then do something
    }

}

暫無
暫無

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

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