當前位置:
首頁 > 知識 > React 組件生命周期

React 組件生命周期

我們將討論 React 組件的生命周期。

組件的生命周期可分成三個狀態:

  • Mounting:已插入真實 DOM

  • Updating:正在被重新渲染

  • Unmounting:已移出真實 DOM

React 組件生命周期

生命周期的方法有:

  • 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毫秒重新設置組件的透明度,並重新渲染:

React 實例

varHello = React.createClass({getInitialState: function(){return{opacity: 1.0}; },
componentDidMount: function(){this.timer = setInterval(function(){varopacity = this.state.opacity; opacity -= .05; if(opacity < 0.1){opacity = 1.0; }this.setState({opacity: opacity}); }.bind(this), 100); },
render: function(){return(
<divstylex={{opacity: this.state.opacity}}> Hello{this.props.name}
</div> ); }});
ReactDOM.render(
<Helloname="world"/>, document.body);

React 組件生命周期

以下實例初始化 statesetNewnumber 用於更新 state。所有生命周期在 Content 組件中。

React 實例

varButton = React.createClass({getInitialState: function(){return{data:0}; }, setNewNumber: function(){this.setState({data: this.state.data + 1})}, render: function(){return(
<div>
<buttononClick = {this.setNewNumber}>INCREMENT</button>
<ContentmyNumber = {this.state.data}></Content>
</div> ); }})varContent = React.createClass({componentWillMount:function(){console.log("Component WILL MOUNT!")}, componentDidMount:function(){console.log("Component DID MOUNT!")}, componentWillReceiveProps:function(newProps){console.log("Component WILL RECEIVE PROPS!")}, shouldComponentUpdate:function(newProps, newState){returntrue; }, 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"));

React 組件生命周期

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

React 編程JSX
React 編程
React 安裝
React 組件

TAG:程序員小新人學習 |