一个 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