React Native 中 component 生命週期

React Native中的component跟Android中的activity,fragment等同樣,存在生命週期,下面先給出component的生命週期圖react

這裏寫圖片描述

getDefaultProps

object getDefaultProps()android

執行過一次後,被建立的類會有緩存,映射的值會存在this.props,前提是這個prop不是父組件指定的 
這個方法在對象被建立以前執行,所以不能在方法內調用this.props ,另外,注意任何getDefaultProps()返回的對象在實例中共享,不是複製緩存

getInitialState

object getInitialState()安全

控件加載以前執行,返回值會被用於state的初始化值服務器

componentWillMount

void componentWillMount()網絡

執行一次,在初始化render以前執行,若是在這個方法內調用setStaterender()知道state發生變化,而且只執行一次框架

render

ReactElement render()函數

render的時候會調用render()會被調用 
調用render()方法時,首先檢查this.propsthis.state返回一個子元素,子元素能夠是DOM組件或者其餘自定義複合控件的虛擬實現 
若是不想渲染能夠返回null或者false,這種場景下,React渲染一個<noscript>標籤,當返回null或者false時,ReactDOM.findDOMNode(this)返回null 
render()方法是很純淨的,這就意味着不要在這個方法裏初始化組件的state,每次執行時返回相同的值,不會讀寫DOM或者與服務器交互,若是必須如服務器交互,在componentDidMount()方法中實現或者其餘生命週期的方法中實現,保持render()方法純淨使得服務器更準確,組件更簡單性能

componentDidMount

void componentDidMount()this

在初始化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()方法,componentWillUpdatecomponentDidUpdate方法也不會被調用

默認狀況下,shouldComponentUpdate方法返回true防止state快速變化時的問題,可是若是·state不變,props只讀,能夠直接覆蓋shouldComponentUpdate用於比較propsstate的變化,決定UI是否更新,當組件比較多時,使用這個方法能有效提升應用性能

componentWillUpdate

void componentWillUpdate(
  object nextProps, object nextState
)

 

propsstate發生變化時執行,而且在render方法以前執行,固然初始化render時不執行該方法,須要特別注意的是,在這個函數裏面,你就不能使用this.setState來修改狀態。這個函數調用以後,就會把nextPropsnextState分別設置到this.propsthis.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(),在這個函數中,能夠作一些組件相關的清理工做,例如取消計時器、網絡請求等

總結

React Native的生命週期就介紹完了,其中最上面的虛線框和右下角的虛線框的方法必定會執行,左下角的方法根據props state是否變化去執行,其中建議只有在componentWillMount,componentDidMount,componentWillReceiveProps方法中能夠修改state

相關文章
相關標籤/搜索