生命周期
組件的生命周期方法對應(yīng)著組件的不同生命階段,通常我們分為三個階段:
1. 組件初始化及掛載階段
2. 組件運(yùn)行期階段
3. 組件卸載階段。

Paste_Image.png
初始化及掛載階段
一、這是組件類的構(gòu)造函數(shù),通常在此初始化state數(shù)據(jù)模型。
constructor(props) {
super(props);
this.state = { //key : value };
}
二、表示組件將要加載到虛擬DOM,在render方法之前執(zhí)行,整個生命周期只執(zhí)行一次。
componentWillMount() {
}
三、表示組件已經(jīng)加載到虛擬DOM,在render方法之后執(zhí)行,整個生命周期只執(zhí)行一次。通常在該方法中完成異步網(wǎng)絡(luò)請求或者集成其他JavaScript庫。
componentDidMount() {
}
運(yùn)行期階段
一、在組件接收到其父組件傳遞的props的時候執(zhí)行,參數(shù)為父組件傳遞的props。在組件的整個生命周期可以多次執(zhí)行。通常在此方法接收新的props值,重新設(shè)置state。
componentWillReceiveProps(nextProps){
this.setState({
//key : value
});
}
二、在componentWillReceiveProps(nextProps)執(zhí)行之后立刻執(zhí)行;或者在state更改之后立刻執(zhí)行。該方法包含兩個參數(shù),分別是props和state。該方法在組件的整個生命周期可以多次執(zhí)行。如果該方法返回false,則componentWillUpdate(nextProps, nextState)及其之后執(zhí)行的方法都不會執(zhí)行,組件則不會進(jìn)行重新渲染。
shouldComponentUpdate(nextProps, nextState) {
return true;
}
二、在shouldComponentUpdate(nextProps, nextState)函數(shù)執(zhí)行完畢之后立刻調(diào)用,該方包含兩個參數(shù),分別是props和state。render()函數(shù)執(zhí)行之前調(diào)用。該方法在組件的整個生命周期可以多次執(zhí)行。
componentWillUpdate(nextProps, nextState) {
}
三、在render()方法執(zhí)行之后立刻調(diào)用。該方法包含兩個參數(shù),分別是props和state。該方法在組件的整個生命周期可以多次執(zhí)行。
componentDidUpdate(preProps, preState) {
}
四、render方法用于渲染組件。在初始化階段和運(yùn)行期階段都會執(zhí)行。
render() {
return(
<View/>
);
}
卸載階段
一、在組件由虛擬DOM卸載的時候調(diào)用。
componentWillUnmount() {
}
注意:
由于this.props和this.state都用于描述組件的特性,可能會產(chǎn)生混淆,一個簡單的區(qū)分方法就是 :
this.props表示那些一旦定義,就不再更改的特性
this.state是會隨著用戶互動而產(chǎn)生改變的特性