一個 React Native 組件從它被 React Native 框架加載,到最終被 React Native 框架卸載,會經歷一個完整的生命週期。在這個生命週期中,我們可以定義一些生命週期函數,用來處理在特定條件下 React Native 組件將要執行的操作。
RN組件的生命週期主要分爲3個部分:
1.裝載組件
constructor: 構造函數,這裏主要對組件的一些狀態進行初始化。
componentWillMount: 準備加載組件,可以在這裏做一些業務初始化操作,或者設置組件狀態。
render: 生成頁面需要的 DOM 結構,並返回該結構。
componentDidMount:組件加載成功並被成功渲染出來後執行。一般會將網絡請求等加載數據的操作放在這裏進行。
2.更新組件
omponentWillReceiveProps:當組件接收到新的 props 時,會觸發該函數。在該函數中,通常可以調用 this.setState 方法來完成對 state 的修改。
shouldComponentUpdate:該方法用來攔截新的 props 或 state,然後根據事先設定好的判斷邏輯,做出最後要不要更新組件的決定。
componentWillUpdate:當上面的方法攔截返回 true 的時候,就可以在該方法中做一些更新之前的操作。
render:根據一系列的 diff 算法,生成需要更新的虛擬 DOM 數據。(注意:在 render 中最好只做數據和模板的組合,不應進行 state 等邏輯的修改,這樣組件結構會更加清晰)
componentDidUpdate:該方法在組件的更新已經同步到 DOM 中去後觸發,我們常在該方法中做 DOM 操作。
3.卸載組件
componentWillUnmount:當組件要被從界面上移除時就會調用。可以在這個函數中做一些相關的清理工作,例如取消計時器、網絡請求等。
調用次數:
constructor 構造函數,初始化需要state 1次
componentWillMount 控件渲染前觸發 1次
render 渲染控件的方法 多次
componentDidMount 控件渲染後觸發 1次
componentWillReceiveProps 組件接收到新的props被調用 多次
shouldComponentUpdate 組件接收到新的props或state時調用 多次
componentWillUpdate 組件接收到新的props或state時調用, 多次
shouldComponentUpdate返回爲true時調用 多次
componentDidUpdate 組件更新後調用 多次
componentWillUnmount 卸載組件調用 1次
小栗子:
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
TextInput,
View,
Text,
Clipboard,
} from 'react-native';
//震動 選debug
export default class MyLifeCircle extends Component {
constructor(props) {
super(props);
console.log('constructor :' + props);
this.state = {message: ' google '};
}
componentWillMount() {
console.log('componentWillMount');
}
//組件接收到新的props時觸發
componentWillReceiveProps(nextProps) {
console.log(" componentWillReceiveProps nextProps: " + nextProps);
}
shouldComponentUpdate(nextProps, nextState) {
console.log(" shouldComponentUpdate:nextProps: " + nextProps + " nextState:" + nextState);
return true;
}
render() {
console.log('render');
return (
<View style={styles.container}>
<Text style={styles.info}>{this.state.message}</Text>
</View>
);
}
//組件加載成功並渲染出來
componentDidMount() {
console.log('componentDidMount');
}
//組件重新渲染前會調用
componentWillUpdate(nextProps, nextState) {
console.log('componentWillUpdate nextProps='+nextProps+" ::: nextState="+nextState);
}
//組件重新渲染後會調用
componentDidUpdate(preProps, nextState) {
console.log('componentDidUpdate');
}
//組件被卸載前會調用
componentWillUnmount() {
console.log('componentWillUnmount');
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 40,
alignItems: 'center',
},
info: {
fontSize: 20,
},
});
日誌:
LOG constructor :[object Object]
LOG componentWillMount
LOG render
LOG componentDidMount