Skip to content

Instantly share code, notes, and snippets.

@azu
Last active September 15, 2016 08:51
Show Gist options
  • Save azu/6ba6863af806bb91ade6ee0ee03fb6be to your computer and use it in GitHub Desktop.
Save azu/6ba6863af806bb91ade6ee0ee03fb6be to your computer and use it in GitHub Desktop.
React Componentのライフサイクル。DOMをアップデートするケース
/*
React Componentのライフサイクル
- setState - componentWillReceiveProps
- かならずimmutableなsetStateにする
- 複数回の更新時は間引かれるので、++のようなインクリメントな処理はしない
- DOMから情報取得 - componentWillUpdate
- DOMの位置を変更 - componentDidUpdate
をそれぞれ書く場所が決まってる
https://facebook.github.io/react/docs/component-specs.html
https://facebook.github.io/react/blog/2016/01/08/A-implies-B-does-not-imply-B-implies-A.html
http://javascript.tutorialhorizon.com/2014/09/13/execution-sequence-of-a-react-components-lifecycle-methods/
http://blog.vjeux.com/2013/javascript/scroll-position-with-react.html
*/
// setStateはcomponentWillReceivePropsで行う
componentWillReceiveProps(nextProps) {
const leftMargin = nextProps.leftMargin;
this.setState({leftMargin});
}
// willでDOMの現在地を取得
componentWillUpdate(nextProps, nextState) {
this.clientLeft = this._element.clientLeft;
}
// didでDOMを新しい位置へ移動
componentDidUpdate(prevProps, prevState) {
// 必要なら this.clientLeftを使う
const leftMargin = this.clientLeft + this.state.leftMargin;
this._element.setAttribute('style', `position:relative; display:block; left:-${leftMargin}px;`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment