此博客基于react-native-0.48.4
生命周期这个词大家一听肯定是不陌生了,在Android中有Activity、Fragment、Service…的生命周期(请原谅我是个小Android);那在ReactNative中组件也是一样有个生命周期的,来引用经典的生命周期流程图:
注意:
- Es5下的
getDefaultProps
在Es6上对应的函数是static defaultProps
- Es5下的
getInitialState
在Es6上对应的函数是constructor(props)
- 整个生命周期主要是分为三部分装载(Mounting)、更新(Updating)、卸载(Unmounting)
- 写一个案例重写这里面的所有生命周期函数来进行测试,加深记忆。
新建一个LifeCycle.js
Component重写生命周期函数。
class LifeCycle extends Component {
constructor(props) {
super(props);
console.log('--constructor--');
}
componentWillMount() {
console.log('--componentWillMount--');
}
render() {
console.log('--render--');
return (
<View style={styles.container}>
<Text>测试生命周期</Text>
</View>
);
}
componentDidMount() {
console.log('--componentDidMount--');
}
shouldComponentUpdate(nextProps,nextState) {
console.log('--shouldComponentUpdate--');
return true;
}
componentWillUpdate(nextProps,nextState) {
console.log('--componentWillUpdate--');
}
componentDidUpdate(nextProps,nextState) {
console.log('--componentDidUpdate--');
}
componentWillUnmount(nextProps,nextState) {
console.log('--componentWillUnmount--');
}
}
生命周期第一部分(装载):我们来运行这个组件并查看log
- 这一部分函数则是上面所提到的组件装载,render()这个函数就是负责渲染界面上的元素,显示文本、按钮、图片…
componentDidMount()
当组件完全渲染完毕后执行,这个函数也会是我们后面学习用的最多的一个。这里就最适合做界面的数据操作了例如:访问网络、数据库操作、数据初始化。
生命周期第二部分(更新):我们来写代码模拟一下
- 在构造函数中定义一个变量
- 如果对State不熟悉的可以先看下文档了解一下
constructor(props) }
- 添加两个文本,一个用来实现点击事件更新State(状态机);一个用来显示
count
变量的值
render() {
return (
<View style={styles.container}>
{}
<Text onPress={() => {
{}
this.setState({
count: this.state.count + 1,})
}}>有本事你点我呀</Text>
<Text>被点了{this.state.count}次</Text>
</View>
);
}
- 当State中的值发生了变化,生命周期就会执行Updating中的函数我们看下执行的效果
- 每点击一次更新State,那么他就会依次执行
shouldComponentUpdate
–>componentWillUpdate
–> render
–>componentDidUpdate
生命周期第三部分(卸载):这里需要在加载这个LifeCycle.js
组件的地方做手脚了,也就是在index.android.js
入口中修改。
//引入LifeCycle组件
var Life = require("./src/js/LifeCycle");
constructor(props) {
super(props);
this.state = {
//定义一个标志位,是否加载组件
remove: false,}
}
render() {
//模拟组件的装载和卸载 生命周期
var view = this.state.remove ? null : <Life/>;
var text = this.state.remove ? "(点击装载)已被卸载" : "(点击卸载)已被装载";
return (
<View style={styles.container}>
{view}
<Text onPress={() => {
this.setState({
remove: !this.state.remove,})
}} style={{marginTop: 15}}>{text}</Text>
</View>
);
}
以上就是一个组件在常规操作中生命周期所执行的顺序,当然在日常开发中肯定就不会是这种常规操作了;这个就以后在讨论了。
源码地址链接
推荐阅读: