簡體   English   中英

如何安全地卸載 React 中的組件?

[英]How to safely unmount a component in React?

通過單擊一個組件中的按鈕,我使用以下代碼刪除父組件中的組件:

// componentA.jsx
class ComponentA extends React.PureComponent {
  removeB() {
    this.setState({ mounted: false })
  }

  renderB() {
    if (!this.state.mounted) {
      return null
    }
    return <ComponentB />
  }

  render() {
    return <div>
      {this.renderB()}
      <ComponentC onClick={this.removeB} />
    </div>
  }
}

// componentB.jsx
class ComponentB extends React.PureComponent {
  render() {
    return ...
  }
}

// componentC.jsx
class ComponentC extends React.PureComponent {
  render() {
    return <Button onClick={this.props.onClick} />
  }
}

我收到錯誤:

無法在“節點”上執行“removeChild”:要刪除的節點不是該節點的子節點。

您的問題是因為函數removeBthis變量引用了錯誤的范圍(在您的示例中, ComponentC的范圍,它應該引用正確的范圍,即ComponentA )。

在傳遞它之前,您應該正確地將事件處理程序綁定到ComponentA的范圍。

您可以通過以下幾種方式做到這一點:

class ComponentA extends React.PureComponent {
  constructor() {
     this.removeB = this.removeB.bind(this);  // Bind event handlers in constructor
  }

  removeB() {
    this.setState({ mounted: false })
  }

  ....

  render() {
    return <div>
      {this.renderB()}
      <ComponentC onClick={this.removeB} />
    </div>
  }
}

或者:

class ComponentA extends React.PureComponent {
  removeB = () => {
    this.setState({ mounted: false })
  } // Using arrow function to bind function to the current lexical scoping

  ....

  render() {
    return <div>
      {this.renderB()}
      <ComponentC onClick={this.removeB} />
    </div>
  }
}

您可以在此處閱讀有關 JS 詞法范圍的更多信息:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

此外,React 文檔在這里提到了將事件處理程序綁定到正確的范圍:

https://reactjs.org/docs/handling-events.html

暫無
暫無

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

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