在Android 和IOS我们都知道组件都有生命周期,RN的组件依旧不例外;
RN组件的生命周期主要分为3个部分
1.装载组件
2.更新组件
3.卸载组件
方法名 | 作用 | 调用次数 |
---|---|---|
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 {Platform, StyleSheet, Text, View} from 'react-native';
export default class LifecycleComponent extends Component {
constructor(props) {
super(props);
console.log("====constructor:props:" + props);
this.state = {
count: 0,
}
}
componentWillMount() {
console.log("====componentWillMount");
}
componentDidMount() {
console.log("====componentDidMount");
}
componentWillReceiveProps(nextProps) {
console.log("====componentWillReceiveProps nextProps:" + nextProps);
}
shouldComponentUpdate(nextProps, nextState) {
console.log("====shouldComponentUpdate:nextProps:" + nextProps + " nextState:" + nextState);
return true;
}
componentWillUpdate() {
console.log("====componentWillUpdate");
}
componentDidUpdate() {
console.log("====componentDidUpdate");
}
componentWillUnmount() {
console.log("====componentWillUnmount");
}
render() {
console.log("====render");
return <View>
<Text onPress={()=>
this.setState({
count:this.state.count+1,
})
}>生命周期:{this.state.count}</Text>
</View>
}
}
这些代码或许记不住,建议安装插件 https://github.com/virtoolswebplayer/ReactNative-LiveTemplate
安装后会自动提示,打开链接会有安装提示;
运行到ios模拟器,command+d 打开js调试工具
google浏览器会出现这样一个页面
单击菜单,打开浏览器控制台
1. 装载组件周期验证
2.卸载组件周期验证
在这里我们通过一个字段动态装载这个带日志的组件,通过字段来卸载和装载效果
.App.js代码如下:
export default class App extends Component<Props> {
constructor(props) {
super(props);
this.state = {
remove: false,
}
}
render() {
var view = this.state.remove ? null : <LifecycleComponent name="life"/>;
var text = this.state.remove ? "装载LifecycleComponent" : "卸载LifecycleComponent";
return (
<View style={styles.container}>
{/* <Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Text style={styles.instructions}>{instructions}</Text>*/}
<HelloComponent name="xxf2"/>
{/*<LifecycleComponent name="life"/>*/}
{view}
<Text onPress={() => {
this.setState({
remove: !this.state.remove,
});
}}>{text}</Text>
</View>
);
}
}
卸载效果如下:
3.更新时执行的生命周期