React 組件生命週期
在本章節中我們將討論React 組件的生命週期。
組件的生命週期可分成三個狀態:
- Mounting:已插入真實DOM
- Updating:正在被重新渲染
- Unmounting:已移出真實DOM
生命週期的方法有:
componentWillMount在渲染前調用,在客戶端也在服務端。
componentDidMount :在第一次渲染後調用,只在客戶端。之後組件已經生成了對應的DOM結構,可以通過this.getDOMNode()來進行訪問。 如果你想和其他JavaScript框架一起使用,可以在這個方法中調用setTimeout, setInterval或者發送AJAX請求等操作(防止異部操作阻塞UI)。
componentWillReceiveProps在組件接收到一個新的prop時被調用。這個方法在初始化render時不會被調用。
shouldComponentUpdate返回一個布爾值。在組件接收到新的props或者state時被調用。 在初始化時或者使用forceUpdate時不被調用。
可以在你確認不需要更新組件時使用。componentWillUpdate在組件接收到新的props或者state但還沒有render時被調用。在初始化時不會被調用。
componentDidUpdate在組件完成更新後立即調用。在初始化時不會被調用。
componentWillUnmount在組件從DOM中移除的時候立刻被調用。
這些方法的詳細說明,可以參考官方文檔 。
以下實例在Hello 組件加載以後,通過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 );
以下實例初始化state ,setNewnumber用於更新state。 所有生命週期在Content組件中。
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') );