借用网上一个RN组件生命周期流程图来做讲解,如下:
介绍组件生命周期前,先对此图做两点说明
1、ES6语法的引入,砍掉了getDefaultProps和getInitialState
- getDefaultProps 使用 static default={}的方式代替
- getInitialState 使用 state属性替代,初始化可以写在constructor里,也可以写成类属性
2、下一代RN版本,生命周期又有改变 详见https://github.com/facebook/react/issues/12152
- componentWillMount–使用componentDidMount代替
- componentWillUpdate–使用componentDidUpdate代替
- componentWillReceiveProps–使用一个新的方法:static getDerivedStateFromProps来代替
下面以一个demo对各个生命周期做详细介绍:
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Button
} from 'react-native';
export default class App extends Component {
constructor() {
super();
console.log("构造函数-->", "constructor");
this.state = {value: 'this is initial state'}
}
static defaultProps = {
prop: 'this is default prop value'
}
/**
* 最先执行的回调函数 ,其在生命周期中只执行一次,这个函数执行完之后,RN马上执行render渲染界面
* 下一代版本 该函数将弃用
*/
componentWillMount(){
console.log("生命周期-->", "componentWillMount");
}
/**
* 渲染界面, 其在生命周期中可能被执行多次 >=1
*/
render(){
console.log("生命周期-->", "render");
return(
<View style={styles.container}>
<Text> 属性初始值:{this.props.value} {'\n'} 状态初始值:{this.state.value}</Text>
<Button title="改变state" onPress={() => {
this.setState({value: 'i changed'})
}}/>
</View>
);
}
/**
* 该函数在生命周期中只执行一次,在第一次render后执行
* 这个函数之后,就进入了稳定运行状态,等待事件触发
*/
componentDidMount(){
console.log("生命周期-->", 'componentDidMount');
}
/**
* 该函数在生命周期中执行 >=0 次 只有在RN组件接受新的props时才会被调用
* 下一代版本 该函数将被static getDerivedStateFromProps替代
*/
componentWillReceiveProps(nextProps){
console.log("生命周期-->", "componentWillReceiveProps " + nextProps.vlaue);
}
/**
* 该函数在生命周期中执行 >=0 次 当RN接受新的state或props时,这个函数将被调用
* 它接收两个object参数,其中第一个是新的props;第二个是新的state。
* 这个函数有一个boolean类型的返回值 如果是false React Native 将不会重新渲染本组件。
*/
shouldComponentUpdate(nextProps, nextState){
console.log("生命周期-->", 'shouldComponentUpdate ' + nextProps.value + " " + nextState.value);
return true;
}
/**
* 如果组件状态或者属性改变,并且上面的 shouldComponentUpdate(...) 返回为 true,
* 就会开始准更新组件,并调用 componentWillUpdate() 该函数在生命周期中执行 >=0 次
* 下一代版本 该函数将弃用
*/
componentWillUpdate(nextProps, nextState){
console.log("生命周期-->", 'shouldComponentUpdate ' + nextProps.value + " " + nextState.value);
}
/**
* 在重新渲染组件完成之后会调用这个函数 该函数在生命周期中执行 >=0 次
*/
componentDidUpdate(prveProps, prveState){
console.log("生命周期-->", 'componentDidUpdate ' + prveProps.value + " " + prveState.value);
}
/**
* 在组件被卸载之前调用。这个函数没有参数,也不需要返回值。
* 在这个函数中,可以做一些组件相关的清理工作,例如取消计时器、网络请求等
*/
componentWillUnmount() {
console.log("生命周期-->",'componentWillUnmount');
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});