如何在 ReactJs 中正确使用 componentWillUnmount()

新手上路,请多包涵

来自官方教程:

componentWillUnmount() 在卸载和销毁组件之前立即调用。在此方法中执行任何必要的清理,例如使计时器无效、取消网络请求或清理在 componentDidMount 中创建的任何 DOM 元素

我理解“使计时器无效”。 fetch 可以用 AbortController 中止。但我不明白“清理在 componentDidMount 中创建的任何 DOM 元素”,我可以看到这种情况的示例吗?

原文由 Ali Ankarali 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 895
2 个回答

如果网络请求发送库支持中止正在进行的网络请求调用,你绝对可以在 componentWillUnmount 方法中调用它。

然而,关于清理 DOM 元素是值得关注的。根据我目前的经验,我将举几个例子。

第一个是——

 import React, { Component } from 'react';

export default class SideMenu extends Component {

    constructor(props) {
        super(props);
        this.state = {
              };
        this.openMenu = this.openMenu.bind(this);
        this.closeMenu = this.closeMenu.bind(this);
    }

    componentDidMount() {
        document.addEventListener("click", this.closeMenu);
    }

    componentWillUnmount() {
        document.removeEventListener("click", this.closeMenu);
    }

    openMenu() {
    }

    closeMenu() {
    }

    render() {
        return (
            <div>
                    <a
                        href      = "javascript:void(0)"
                        className = "closebtn"
                        onClick   = {this.closeMenu}
                    >
                        ×
                    </a>
                  <div>
                     Some other structure
                  </div>
                </div>
        );
    }
}

在这里,我删除了我在安装组件时添加的点击事件监听器。

第二个是——

 import React from 'react';
import { Component } from 'react';
import ReactDom from 'react-dom';
import d3Chart from './d3charts';

export default class Chart extends Component {

    static propTypes = {
            data: React.PropTypes.array,
            domain: React.PropTypes.object
    };

    constructor(props){
        super(props);

    }

    componentDidMount(){
        let el = ReactDom.findDOMNode(this);
        d3Chart.create(el, {
            width: '100%',
            height: '300px'
        }, this.getChartState());
    }

    componentDidUpdate() {
        let el = ReactDom.findDOMNode(this);
        d3Chart.update(el, this.getChartState());
    }

    getChartState() {
        return {
            data: this.props.data,
            domain: this.props.domain
        }
    }

    componentWillUnmount() {
        let el = ReactDom.findDOMNode(this);
        d3Chart.destroy(el);
    }

    render() {
        return (
            <div className="Chart">
            </div>
        );
    }
}

在这里,我试图将 d3.js 与 react 集成到 componentWillUnmount 中;我正在从 DOM 中删除图表元素。

除此之外,我还使用 componentWillUnmount 来清理打开后的引导模式。

我确信还有很多其他用例,但这些是我使用过的案例 componentWillUnMount 。我希望它能帮助你。

原文由 WitVault 发布,翻译遵循 CC BY-SA 4.0 许可协议

在这个简单的示例中(示例取自 React Docs),我使用它来清除时钟组件的间隔。例如,在您的页面中,您有 2 个选项卡,其中一个显示 User Info ,第二个选项卡显示 User Schedule 显示那里的实时时钟。一旦切换到 User Schedule 选项卡, componentDidMount 将被调用以设置计时器。一旦你切换回 User Info ,就没有必要保留这个间隔挂钩,你可以在 componentWillUnmount 事件中编写你的取消绑定/取消订阅逻辑。

 import React from "react";
export default class Clock extends React.Component {
  constructor(props) {
    console.log("Clock", "constructor");
    super(props);
    this.state = {
      date: new Date()
    };
  }
  tick() {
    this.setState({
      date: new Date()
    });
  }
  // These methods are called "lifecycle hooks".
  componentDidMount() {
    console.log("Clock", "componentDidMount");
    this.timerID = setInterval(() => {
      this.tick();
    }, 1000);
  }
  // These methods are called "lifecycle hooks".
  componentWillUnmount() {
    console.log("Clock", "componentWillUnmount");
    clearInterval(this.timerID);
  }
  render() {
    return (
        <div>It is {this.state.date.toLocaleTimeString()}.</div>
    );
  }
}

原文由 Teoman shipahi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题