實例化
首次實例化
getDefaultProps
getInitialState
componentWillMount
render
componentDidMount
實例化完成后的更新
getInitialState
componentWillMount
render
componentDidMount
存在期
組件已存在時的狀態(tài)改變
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate
銷毀&清理期
componentWillUnmount
說明
生命周期共提供了10個不同的API舍败。
1.getDefaultProps
作用于組件類,只調(diào)用一次,返回對象用于設(shè)置默認(rèn)的props脂凶,對于引用值浪册,會在實例中共享扫腺。
2.getInitialState
作用于組件的實例,在實例創(chuàng)建時調(diào)用一次村象,用于初始化每個實例的state笆环,此時可以訪問this.props。
3.componentWillMount
在完成首次渲染之前調(diào)用厚者,此時仍可以修改組件的state躁劣。
4.render
必選的方法,創(chuàng)建虛擬DOM库菲,該方法具有特殊的規(guī)則:
只能通過this.props和this.state訪問數(shù)據(jù)
可以返回null账忘、false或任何React組件
只能出現(xiàn)一個頂級組件(不能返回數(shù)組)
不能改變組件的狀態(tài)
不能修改DOM的輸出
5.componentDidMount
真實的DOM被渲染出來后調(diào)用,在該方法中可通過this.getDOMNode()訪問到真實的DOM元素熙宇。此時已可以使用其他類庫來操作這個DOM鳖擒。
在服務(wù)端中,該方法不會被調(diào)用奇颠。
6.componentWillReceiveProps
組件接收到新的props時調(diào)用败去,并將其作為參數(shù)nextProps使用,此時可以更改組件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)用的瓶頸時吓妆,可通過該方法進(jìn)行適當(dāng)?shù)膬?yōu)化。
在首次渲染期間或者調(diào)用了forceUpdate方法后吨铸,該方法不會被調(diào)用
8.componentWillUpdate
接收到新的props或者state后行拢,進(jìn)行渲染之前調(diào)用,此時不允許更新props或state诞吱。
9.componentDidUpdate
完成渲染新的props或者state后調(diào)用舟奠,此時可以訪問到新的DOM元素竭缝。
10.componentWillUnmount
組件被移除之前被調(diào)用,可以用于做一些清理工作沼瘫,在componentDidMount方法中添加的所有任務(wù)都需要在該方法中撤銷抬纸,比如創(chuàng)建的定時器或添加的事件監(jiān)聽器。