您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

如果网络请求发送库支持中止正在进行的网络请求调用,则绝对可以在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。希望对您有帮助。

其他 2022/1/1 18:13:54 有537人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶