[TIL]React Class Lifecycle-一般タイプ編について



Lifecycle


クラスの要素を学ぶときに最も重要だと思いますが、実際に最も重要なのはこのライフサイクルです.
Lifecycleは、名前の通りライフサイクルを表し、クラスコンポーネントにはMount、Update、Unmountで使用されるLifecycleメソッドがあります.いくつかのタイプのLifecycleは、次のタイプだけではなく、あまり一般的ではないタイプで、実際にテストで理解したものだけを整理しました.

を選択します。


Mount


Constuctor

constructor(props) {
  super(props);
  this.state = {
    value: ""
  };
  this.handleClick = this.handleClick.bind(this);
}
コンストラクション関数は、this.stateにオブジェクトを割り当てて地域ステータスを初期化するか、インスタンスでバッチ・メソッドをバインドします.

render

render() {
   return (
      <div>안녕하세요</div>
   )
}
レンダーはマウント時のみの使い方ではありませんが、マウント時にも使ったことがあるので試してみました.
renderはクラスコンポーネントで宣言する必要がある方法です.通常は同じ構造を持っていますが、戻るときに生成された構造をJSXとして返します.

componentDidMount


componentDidMountは、コンポーネントをインストールした直後にレンダリングによって呼び出されます.最も使いやすいのは、外部からデータをロードするときかもしれません.

Update


更新ポイントの基準は、新しいpropsが受信された場合、またはsetStateによってステータス値が変更された場合、render->dom update->コンポーネントDidUpdateの順に行います.

componentDidUpdate

componentDidUpdate(prevProps) {
  // 전형적인 사용 사례 (props 비교를 잊지 마세요)
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}
ComponentDidUpdateが更新時に呼び出されるように、条件文ではなくComponentDidUpdateでstateを呼び出すと、値を変更するたびに呼び出され、無限に繰り返される可能性があります.
ここでは,従来と現在のpropsを比較し,ネットワークリクエストなどを送信する作業が望ましい.

Unmount


componentWillUnmount


コンポーネントWillUnmountは、構成部品をアンインストールする前に呼び出されます.ここでは、cleartimeout、ネットワークリクエストのキャンセル、コンポーネントDidMountで作成したサブスクリプションのキャンセルなど、必要なすべてのクリーンアップ操作を実行できます.
ちなみに、アンインストールが完了すると、絶対に再ロードされません

直接コードを使用してライフサイクルを理解する

import React from 'react';

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      inputValue: 'default',
    };
    console.log(`Constructor: ${this.state.inputValue}`);
  }

  componentDidMount() {
    console.log(`componentDidMount: ${this.state.inputValue}`);
  }

  componentDidUpdate() {
    console.log(`componentDidUpdate: ${this.state.inputValue}`);
  }

  onChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  render() {
    console.log(`render: ${this.state.inputValue}`);
    return (
      <div>
        <input
          type="text"
          name="inputValue"
          value={this.state.inputValue}
          onChange={this.onChange}
        />
      </div>
    );
  }
}

export default App;

上のダイナミックマップの手順のように、1回目のリフレッシュとマウントが発生した場合は、Constructor、Render、ComponentDidMountの順に呼び出され、入力値を変更するとステータス値の変化に伴って更新され、Render、ComponentDidUpdateが呼び出されます.
本や文章で読んでいるときは茫然としていて、簡単なコードでも一節編んでいて、理解しましたが、流暢に読むより実習が一番です.

ソース


https://ko.reactjs.org/docs/react-component.html#constructor
https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/