How to properly use componentWillUnmount() in ReactJs

前端 未结 4 1139
谎友^
谎友^ 2020-12-23 19:18

From the official tutorial:

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any nece

4条回答
  •  轮回少年
    2020-12-23 19:52

    If the network request sending library supports aborting the ongoing network request call, you can definitely call that in componentWillUnmount method.

    However in relation to cleaning up of DOM elements is of concern. I will give a couple of examples, based on my current experience.

    First one is -

    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 (
                
    ×
    Some other structure
    ); } }

    Here I am removing the click event listener which I added when the component mounted.

    Second one is -

    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 (
                
    ); } }

    Here I am trying to integrate d3.js with react into componentWillUnmount; I am removing the chart element from the DOM.

    Apart from that I have used componentWillUnmount for cleaning up bootstrap modals after opening.

    I am sure there are tons of other use cases out there, but these are the cases where I have used componentWillUnMount. I hope it helps you.

提交回复
热议问题