コンポーネントのライフサイクルを反応させます2024 年の最新の入門チュートリアル。このコースでは コンポーネントのライフサイクルを反応させます について学習できます。
この章では、コンポーネントを反応させ、ライフサイクルについて説明します。
コンポーネントのライフサイクルは、3つの状態に分けることができます。
ライフサイクルの方法は次のとおりです。
また通話、クライアント側のサービスをレンダリングする前にcomponentWillMount。
componentDidMount:クライアントのみをレンダリングする最初の呼び出しの後。コンポーネントは、DOM構造に対応する生成された後、)(this.getDOMNodeを介してアクセスすることができます。 あなたは他のJavaScriptフレームワークで使用する場合(別の単位操作は、UIをブロックしないようにするために)、あなたは、このメソッドのsetTimeout、setIntervalというを呼び出すことができますかなど、AJAX要求を送信します。
コンポーネントが新しい小道具を受信したときにcomponentWillReceivePropsが呼び出されます 。 この方法は、レンダリング初期化中に呼び出されません。
shouldComponentUpdateはブール値を返します。コンポーネントが新しい小道具や状態を受信したときに呼び出されます。 これは、初期化時に呼び出されるかforceUpdateを使用していません。
更新されたコンポーネントを確認する必要がない場合に使用することができます。
コンポーネント内のcomponentWillUpdateは、新しい小道具や状態を受信しないが、何のレンダリングと呼ばれています。 これは、初期化時に呼び出されません。
更新後すぐに呼ばれる完全なcomponentDidUpdateコンポーネントです。 これは、初期化時に呼び出されません。
コンポーネントは、DOMから削除されたときにすぐに呼ばcomponentWillUnmount。
これらの方法の詳細な説明は、あなたはを参照することができます公式ドキュメント 。
以下の例のコンポーネントは、ロードされたタイマーcomponentDidMount法により100ミリ秒ごとに透明度のリセット成分と再レンダリングを設定されているハローた後:
var Hello = React.createClass({ getInitialState: function () { return { opacity: 1.0 }; }, componentDidMount: function () { this.timer = setInterval(function () { var opacity = this.state.opacity; opacity -= .05; if (opacity < 0.1) { opacity = 1.0; } this.setState({ opacity: opacity }); }.bind(this), 100); }, render: function () { return ( <div style={{opacity: this.state.opacity}}> Hello {this.props.name} </div> ); } }); ReactDOM.render( <Hello name="world"/>, document.body );
次の例では、状態を更新するため、setNewnumberを状態に初期化されます。すべてのライフサイクルコンテンツコンポーネント 。
var Button = React.createClass({ getInitialState: function() { return { data:0 }; }, setNewNumber: function() { this.setState({data: this.state.data + 1}) }, render: function () { return ( <div> <button onClick = {this.setNewNumber}>INCREMENT</button> <Content myNumber = {this.state.data}></Content> </div> ); } }) var Content = React.createClass({ componentWillMount:function() { console.log('Component WILL MOUNT!') }, componentDidMount:function() { console.log('Component DID MOUNT!') }, componentWillReceiveProps:function(newProps) { console.log('Component WILL RECIEVE PROPS!') }, shouldComponentUpdate:function(newProps, newState) { return true; }, componentWillUpdate:function(nextProps, nextState) { console.log('Component WILL UPDATE!'); }, componentDidUpdate:function(prevProps, prevState) { console.log('Component DID UPDATE!') }, componentWillUnmount:function() { console.log('Component WILL UNMOUNT!') }, render: function () { return ( <div> <h3>{this.props.myNumber}</h3> </div> ); } }); ReactDOM.render( <div> <Button /> </div>, document.getElementById('example') );