1. 程式人生 > >React Native 中 component 生命週期

React Native 中 component 生命週期

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

這裡寫圖片描述

getDefaultProps

object getDefaultProps()

執行過一次後,被建立的類會有快取,對映的值會存在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()

在初始化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