LoginSignup
1
0

More than 3 years have passed since last update.

React初心者が、React.Componentのライフサイクルを理解する

Posted at

React.Componentには、
- Mounting
- Updating
- Unmounting

があります。それぞれで呼び出される関数があり、それらを実装すると、コンポーネント自体のライフサイクルを操作できる。

Mounting

  1. constructor(props)
  2. static getDerivedStateFromProps(nextProps, prevState)
  3. componentWillMount() / UNSAFE_componentWillMount()
  4. render()
  5. componentDidMount()

それぞれの関数の説明

constructor()

コンポーネっとのクラス自体のコンストラクタです。
super()を実行することが必須で、受け取ったpropsを処理する
stateの初期化もこの段階で行う。

static getDerivedStateFromProps(nextProps, prevState)

propsとstateを確認して、propsによってstateを書き換えるかどうかを決定する。
書き換えが必要であれば、書き換え後のstateを作成し、その値を返す。
書き換えが不要であれば、nullを返す。
この関数を通すため、コンストラクタがstateは初期化しておくべき!

componentWillMount() / UNSAFE_componentWillMount()

React0.17ではいしされる。
安全でないので使わない

render()

描画を扱う関数。

componentDidMount()

コンポーネントのMountionの処理が全て完了した際に呼び出される関数で、コンポーネントで一度だけ呼び出される。
一般には、コンストラクタでstateの箱を作り、componentDidMount()から必要なデータを取得しにいくような処理を記述。

Updating

  1. componentWillReceiveProps(props) / UNSAFE_componentWillReceiveProps()
  2. static getDerivedStateFromProps(nextProps, preState)
  3. shouldComponentUpdate(nextProps, nextState)
  4. componentWIllUpdate() / UNSAFE_componentWillUpdate()
  5. render()
  6. getSnapshotBeforeUpdate(prevProps, prevState)
  7. componentDidUpdate(prevProps, prevState,snapshot)

それぞれの関数の説明

shouldComponentUpdate(nextProps, nextState)

コンポーネントのアップデータが必要かどうかを判断するための関数。

getSnapshotBeforeUpdate(prevProps, prevState)

UPdatingの処理でrender()のあとに呼び出され、この関数でreturnされる値がcomponentDIdUpdateのsnapshotとして呼び出される。

Uumounting

  1. componentWIllUnmount()

それぞれの関数の説明

componentWIllUnmount()

メモリリークを抑えるために参照の削除などを実装

参照

React Native+Expoではじめるスマホアプリ開発

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0