Reactに挑戦してみる 3
概要
React参考書籍を読んでみる。
参考書籍
WebデベロッパーのためのReact開発入門 JavaScript UIライブラリの基本と活用
- 作者: 柴田文彦
- 出版社/メーカー: インプレス
- 発売日: 2016/11/25
- メディア: 単行本(ソフトカバー)
- この商品を含むブログを見る
やってみたこと
- ライフサイクルについて
ライフサイクルメソッドについて
React既定のメソッドに従って、コンポーネントを変化させて行く仕組み。7つある模様
- componentWillMount:マウント直前に1回呼び出されるメソッド
- componentDidMount:マウント直後に1回呼び出されるメソッド
- componentWillReceiveProps:コンポーネントに新たなプロパティがセットされるたびに呼び出されるメソッド
- shouldComponentUpdate:コンポーネントを更新して良いか(プロパティ、ステートが変更)を確認するメソッド
- componentWillUpdate:コンポーネントが実際に更新される直前に呼び出されるメソッド
- componentDidUpdate:コンポーネントが更新された直後に呼び出されるメソッド
- componentWillUnmount:コンポーネントが閉じられる直前に呼び出されるメソッド
マウント->ページが開かれて、その上に配置されているコンポーネントが最初に描画される
ライフサイクルシーケンスの例
componentWillMount -> renderメソッド -> componentDidMount
shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate (ステートが変更された)
componentWillReceiveProps -> shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate (プロパティが変更される)
試しにサンプルを書いてみる。。。
var Evaluator = React.createClass({ componentWillMount: function(){ console.log('componentWillMount:'); }, componentDidMount: function(){ console.log('componentDidMount:'); }, componentWillReceiveProps: function(nextProps){ console.log('componentWillReceiveProps:', nextProps); }, shouldComponentUpdate: function(nextProps, nextState){ console.log('shouldComponentUpdate:', nextProps, nextState); return true; }, componentWillUpdate: function(nextProps, nextState){ console.log('componentWillUpdate:', nextProps, nextState); }, componentDidUpdate: function(prevProps, prevState){ console.log('componentDidUpdate:', prevProps, prevState); }, componentWillUnmount: function(){ console.log('componentWillUnmount:'); }, getInitialState: function(){ return{ expression: '' }; }, reCalcValue: function(e){ if (e.key === 'Enter') this.setState({ expression: e.target.value }); }, render: function(){ return React.DOM.div( null, React.DOM.input({ type: 'text', onKeyPress: this.reCalcValue }), React.DOM.h2(null, eval(this.state.expression)) ); } }); ReactDOM.render( React.createElement(Evaluator), document.getElementById('content') );
これをjsfiddleでやると以下のような感じでconsole logに表示してくれる!
componentWillMount: (index):50 componentDidMount: (index):56 shouldComponentUpdate: Object {} Object {expression: "5+4"} (index):60 componentWillUpdate: Object {} Object {expression: "5+4"} (index):63 componentDidUpdate: Object {} Object {expression: ""}