ReactJsでcomponentWillUnmount()を適切に使用する方法 質問する

ReactJsでcomponentWillUnmount()を適切に使用する方法 質問する

公式チュートリアルより:

componentWillUnmount()コンポーネントがアンマウントされ破棄される直前に呼び出されます。このメソッドでは、タイマーの無効化、ネットワークリクエストのキャンセル、または作成されたDOM要素のクリーンアップなど、必要なクリーンアップを実行します。componentDidMount

「タイマーの無効化」は理解できました。fetchは で中止できますAbortController。 しかし、「 で作成された DOM 要素をクリーンアップするcomponentDidMount」は理解できません。その場合の例を見ることはできますか?

ベストアンサー1

ネットワーク要求送信ライブラリが進行中のネットワーク要求呼び出しの中止をサポートしている場合は、そのcomponentWillUnmountメソッドを確実に呼び出すことができます。

しかし、要素のクリーンアップに関してはDOM懸念事項があります。私の現在の経験に基づいて、いくつかの例を挙げます。

まず1つ目は -

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

ここでは、コンポーネントがマウントされたときに追加したクリック イベント リスナーを削除しています。

2つ目は -

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.jsreact を統合しようとしていますcomponentWillUnmount。DOM からチャート要素を削除しています。

componentWillUnmountそれ以外にも、ブートストラップ モーダルを開いた後にクリーンアップするために使用しました。

他にもたくさんの使用例があると思いますが、私が使用した例は以上ですcomponentWillUnMount。お役に立てれば幸いです。

おすすめ記事