小编典典

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

reactjs

从官方教程中:

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

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


阅读 906

收藏
2020-07-22

共1个答案

小编典典

如果网络请求发送库支持中止正在进行的网络请求调用,则绝对可以在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>
        );
    }
}

在这里,我将删除在安装组件时添加的click事件侦听器。

第二个是-

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与反应融为一体componentWillUnmount; 我正在从DOM中删除图表元素。

除此之外,我还用于componentWillUnmount在打开后清理引导程序模式。

我敢肯定还有很多其他用例,但是这些都是我用过的用例componentWillUnMount。希望对您有帮助。

2020-07-22