24.React|Mount/Unmount
Unmount…って何やったっけ?ってなったのでおさらい…。
Mount
- ReactコンポーネントがDOMツリーに追加されること。
Unmount
- ReactコンポーネントがDOMツリーから削除されること。
UNSAFE_componentWillMount()
- コンポーネントがDOMにマウントされる直前に呼び出される。
componentWillMount
という名前から変更となった(componentWillMount
はバージョン17まで機能し続ける)。
なお現在ではこのライフサイクルメソッドは非推奨となっている。
ES6以前のconstructorが存在しなかった時には、初期化処理を行うのに適していた。
下記のようにconstructor
を使用するように修正すると良い。
- 変更前
class Hello extends React.Component { componentWillMount() { doSomething(); } render() { return <div>{this.state.name} </div> } }
- 変更後
class Hello extends React.Component { constructor(props) { super(props); doSomething(); } render() { return <div>{this.state.name} </div> } }
componentDidMount()
- コンポーネントがDOMにマウントされた直後に呼び出される。
DOMに関わる初期化処理を行いたい時に便利。