Skip to content

Instantly share code, notes, and snippets.

@kaisugi
Last active March 29, 2019 10:22
Show Gist options
  • Save kaisugi/26c33e484db6460e8b1b6b026189243b to your computer and use it in GitHub Desktop.
Save kaisugi/26c33e484db6460e8b1b6b026189243b to your computer and use it in GitHub Desktop.
今時(2019年3月)の React Lifecycle

componentWillReceiveProps が今は legacy になっているのを知らずに使っていてびっくりしたので、https://reactjs.org/docs/react-component.html から知らなかった部分をメモ

よく使うやつ

render()

はい
shouldComponentUpdate() が false を返すときは発火しない

constructor()

super(props);は忘れないように
this.state の初期化とイベントハンドラーの bind に使いましょう
props をそのまま state にするのはバグるのでやってはいけない

componentDidMount()

初期時に起こす副作用を書く。データを引っ張ってくるとか。
なんか設定を加えたときは componentWillUnmount() で戻すのを忘れないように

componentDidUpdate()

prevProps, prevState, snapshot を引数に取ります。もちろん省いてもよい
propsやstateの変化時に起こす副作用を書く。今はpropsの変化に対応する動作は componentWillReceiveProps ではなくこれを使う
shouldComponentUpdate() が false を返すときは発火しない
snapshot とかいうのはレアなのでよく知らなくてよさそう

componentWillUnmount()

Component が消えた時

あんま使わないやつ

shouldComponentUpdate()

render()componentDidUpdate() を起こさせない

static getDerivedStateFromProps()

レアなので知らなくてよさそうな雰囲気がある

getSnapshotBeforeUpdate()

DOMが変化を起こす前に、起こす前の情報を何らかの形で保持したいときに使うっぽいが、あまり使わなさそうなもの。ドキュメンテーションには例としてスクロール位置が挙げられている

エラーハンドリング

知りたくなったら https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.htmlhttps://reactjs.org/docs/react-component.html#error-boundaries を読みましょう

その他 Lifecycle とは直接関係ないもの

setState()

はい

forceUpdate()

re-render をどうしてもすぐ起こさせたいとき

defaultProps

Componentの中に値が直接書かれていない時のデフォルトのpropsの値を決められる。便利そう

displayName

デバッグに使う? https://reactjs.org/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment