實(shí)例化
首次實(shí)例化
getDefaultProps
getInitialState
componentWillMount
render
componentDidMount
實(shí)例化完成后的更新
getInitialState
componentWillMount
render
componentDidMount
存在期
組件已存在時(shí)的狀態(tài)改變
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate
銷毀&清理期
componentWillUnmount
說明
生命周期共提供了10個(gè)不同的API。
1.getDefaultProps
作用于組件類,只調(diào)用一次,返回對(duì)象用于設(shè)置默認(rèn)的props,對(duì)于引用值,會(huì)在實(shí)例中共享。
2.getInitialState
作用于組件的實(shí)例,在實(shí)例創(chuàng)建時(shí)調(diào)用一次,用于初始化每個(gè)實(shí)例的state,此時(shí)可以訪問this.props。
3.componentWillMount
在完成首次渲染之前調(diào)用,此時(shí)仍可以修改組件的state。
4.render
必選的方法,創(chuàng)建虛擬DOM,該方法具有特殊的規(guī)則:
只能通過this.props和this.state訪問數(shù)據(jù)
可以返回null、false或任何React組件
只能出現(xiàn)一個(gè)頂級(jí)組件(不能返回?cái)?shù)組)
不能改變組件的狀態(tài)
不能修改DOM的輸出
5.componentDidMount
真實(shí)的DOM被渲染出來后調(diào)用,在該方法中可通過this.getDOMNode()訪問到真實(shí)的DOM元素。此時(shí)已可以使用其他類庫來操作這個(gè)DOM。
在服務(wù)端中,該方法不會(huì)被調(diào)用。
6.componentWillReceiveProps
組件接收到新的props時(shí)調(diào)用,并將其作為參數(shù)nextProps使用,此時(shí)可以更改組件props及state。
componentWillReceiveProps: function(nextProps) {
if (nextProps.bool) {
this.setState({
bool: true
});
}
}
7.shouldComponentUpdate
組件是否應(yīng)當(dāng)渲染新的props或state,返回false表示跳過后續(xù)的生命周期方法,通常不需要使用以避免出現(xiàn)bug。在出現(xiàn)應(yīng)用的瓶頸時(shí),可通過該方法進(jìn)行適當(dāng)?shù)膬?yōu)化。
在首次渲染期間或者調(diào)用了forceUpdate方法后,該方法不會(huì)被調(diào)用
8.componentWillUpdate
接收到新的props或者state后,進(jìn)行渲染之前調(diào)用,此時(shí)不允許更新props或state。
9.componentDidUpdate
完成渲染新的props或者state后調(diào)用,此時(shí)可以訪問到新的DOM元素。
10.componentWillUnmount
組件被移除之前被調(diào)用,可以用于做一些清理工作,在componentDidMount方法中添加的所有任務(wù)都需要在該方法中撤銷,比如創(chuàng)建的定時(shí)器或添加的事件監(jiān)聽器。