1. 程式人生 > >react生命周期鉤子

react生命周期鉤子

prop ext target function rep targe blog 覆蓋 obj

大家先看一張關於組件掛載的經典的圖片:

技術分享圖片

下面一一說一下這幾個生命周期的意義:

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生命周期鉤子