生命周期
組件的生命周期方法對應(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)生改變的特性