【问题标题】:how to we can remove a component React from the DOM using componentWillUnmount() method? [closed]我们如何使用 componentWillUnmount() 方法从 DOM 中删除组件 React? [关闭]
【发布时间】:2020-04-28 19:18:07
【问题描述】:

我什么时候可以在我的 React 代码中使用以下方法? componentWillUnmount()

请举个例子。

【问题讨论】:

标签: javascript reactjs dom


【解决方案1】:

如果您的意图是删除组件或元素,您应该通过条件渲染来完成,因此,更改渲染组件的状态。

【讨论】:

    【解决方案2】:

    “我什么时候可以在我的 React 代码中使用以下方法?componentWillUnmount()”:

    我们希望在第一次将时钟渲染到 DOM 时设置一个计时器。这在 React 中称为“挂载”。

    我们还想在 Clock 生成的 DOM 被删除时清除该计时器。这在 React 中称为“卸载”。

    componentDidMount() 方法在组件输出被渲染到 DOM 后运行。这是设置计时器的好地方:

      componentDidMount() {
        this.timerID = setInterval(
          () => this.tick(),
          1000
        );
      }
    

    我们将在 componentWillUnmount() 生命周期方法中拆除计时器:

      componentWillUnmount() {
        clearInterval(this.timerID);
      }
    

    本质上,当您需要在当前看到的 DOM 被丢弃之前做某事时,就会使用 componentWillUnmount() 方法。在这种情况下,时钟将从 DOM 中删除,因此您希望在此之前停止计时器。

    您可以在此处阅读有关生命周期方法的更多信息:https://reactjs.org/docs/state-and-lifecycle.html

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 2022-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 2017-01-16
      • 2017-12-13
      • 2019-06-14
      相关资源
      最近更新 更多