參考資料:http://blog.csdn.net/ElinaVampire/article/details/51813677javascript
你們先看一張關於組件掛載的經典的圖片:html
下面一一說一下這幾個生命週期的意義:java
getDefaultProps
object getDefaultProps()
react
執行過一次後,被建立的類會有緩存,映射的值會存在this.props
,前提是這個prop不是父組件指定的
這個方法在對象被建立以前執行,所以不能在方法內調用this.props
,另外,注意任何getDefaultProps()
返回的對象在實例中共享,不是複製緩存
getInitialState
object getInitialState()
安全
控件加載以前執行,返回值會被用於state的初始化值服務器
componentWillMount
void componentWillMount()
網絡
執行一次,在初始化render
以前執行,若是在這個方法內調用setState
,render()
知道state發生變化,而且只執行一次框架
render
ReactElement render()
函數
render的時候會調用render()
會被調用
調用render()
方法時,首先檢查this.props
和this.state
返回一個子元素,子元素能夠是DOM組件或者其餘自定義複合控件的虛擬實現
若是不想渲染能夠返回null或者false,這種場景下,react渲染一個<noscript>
標籤,當返回null或者false時,ReactDOM.findDOMNode(this)
返回null
render()
方法是很純淨的,這就意味着不要在這個方法裏初始化組件的state,每次執行時返回相同的值,不會讀寫DOM或者與服務器交互,若是必須如服務器交互,在componentDidMount()
方法中實現或者其餘生命週期的方法中實現,保持render()
方法純淨使得服務器更準確,組件更簡單
componentDidMount
void componentDidMount()
在初始化render以後只執行一次,在這個方法內,能夠訪問任何組件,componentDidMount()
方法中的子組件在父組件以前執行
從這個函數開始,就能夠和 js 其餘框架交互了,例如設置計時 setTimeout 或者 setInterval,或者發起網絡請求
shouldComponentUpdate
boolean shouldComponentUpdate( object nextProps, object nextState }
這個方法在初始化render
時不會執行,當props或者state發生變化時執行,而且是在render
以前,當新的props
或者state
不須要更新組件時,返回false
shouldComponentUpdate: function(nextProps, nextState) { return nextProps.id !== this.props.id; }
當shouldComponentUpdate
方法返回false時,就不會執行render()
方法,componentWillUpdate
和componentDidUpdate
方法也不會被調用
默認狀況下,shouldComponentUpdate
方法返回true防止state
快速變化時的問題,可是若是·state
不變,props
只讀,能夠直接覆蓋shouldComponentUpdate
用於比較props
和state
的變化,決定UI是否更新,當組件比較多時,使用這個方法能有效提升應用性能
componentWillUpdate
void componentWillUpdate( object nextProps, object nextState )
當props
和state
發生變化時執行,而且在render
方法以前執行,固然初始化render時不執行該方法,須要特別注意的是,在這個函數裏面,你就不能使用this.setState
來修改狀態。這個函數調用以後,就會把nextProps
和nextState
分別設置到this.props
和this.state
中。緊接着這個函數,就會調用render()
來更新界面了
componentDidUpdate
void componentDidUpdate( object prevProps, object prevState )
組件更新結束以後執行,在初始化render
時不執行
componentWillReceiveProps
void componentWillReceiveProps( object nextProps )
當props
發生變化時執行,初始化render
時不執行,在這個回調函數裏面,你能夠根據屬性的變化,經過調用this.setState()
來更新你的組件狀態,舊的屬性仍是能夠經過this.props
來獲取,這裏調用更新狀態是安全的,並不會觸發額外的render
調用
componentWillReceiveProps: function(nextProps) { this.setState({ likesIncreasing: nextProps.likeCount > this.props.likeCount }); }
componentWillUnmount
void componentWillUnmount()
當組件要被從界面上移除的時候,就會調用componentWillUnmount()
,在這個函數中,能夠作一些組件相關的清理工做,例如取消計時器、網絡請求等
只有深入理解了reactnative的生命週期,才能更好的理解大牛寫的代碼!!!
做者介紹:半路學IT,作開發3年,先就任在一家共享單車公司,作後臺開發!
我開了一個公衆號,歡迎各位有志同道合朋友,關注!不按期分享幹活,和我得故事!