React Native 生命周期

###这篇文章转载自:https://blog.csdn.net/zy_flyway/article/details/77303601

前言:

这篇主要学习RN的生命周期,在开发中如果掌握了并熟练的运用生命周期函数的话,往往开发能事半功倍。

React Native生命周期简介





如图,可以把组件生命周期大致分为三个阶段:

  • 第一阶段:是组件第一次绘制阶段,如图中的上面虚线框内,在这里完成了组件的加载和初始化;
  • 第二阶段:是组件在运行和交互阶段,如图中左下角虚线框,这个阶段组件可以处理用户交互,或者接收事件更新界面;
  • 第三阶段:是组件卸载消亡的阶段,如图中右下角的虚线框中,这里做一些组件的清理工作。

生命周期回调函数(ES5写法)

下面来详细介绍生命周期中的各回调函数,先说下和上图对应的ES5写法。

getDefaultProps

在组件创建之前,会先调用 getDefaultProps(),这是全局调用一次,严格地来说,这不是组件的生命周期的一部分。在组件被创建并加载候,首先调用 getInitialState(),来初始化组件的状态。

componentWillMount

然后,准备加载组件,会调用 componentWillMount(),其原型如下:


     
     
  1. void componentWillMount()

这个函数调用时机是在组件创建,并初始化了状态之后,在第一次绘制 render() 之前。可以在这里做一些业务初始化操作,也可以设置组件状态。这个函数在整个生命周期中只被调用一次。

componentDidMount

在组件第一次绘制之后,会调用 componentDidMount(),通知组件已经加载完成。函数原型如下:


     
     
  1. void componentDidMount()

这个函数调用的时候,其虚拟 DOM 已经构建完成,你可以在这个函数开始获取其中的元素或者子组件了。需要注意的是,RN 框架是先调用子组件的 componentDidMount(),然后调用父组件的函数。从这个函数开始,就可以和 JS 其他框架交互了,例如设置计时 setTimeout 或者 setInterval,或者发起网络请求。这个函数也是只被调用一次。这个函数之后,就进入了稳定运行状态,等待事件触发。

componentWillReceiveProps

如果组件收到新的属性(props),就会调用 componentWillReceiveProps(),其原型如下:


     
     
  1. void componentWillReceiveProps(
  2. object nextProps
  3. )

输入参数 nextProps 是即将被设置的属性,旧的属性还是可以通过 this.props 来获取。在这个回调函数里面,你可以根据属性的变化,通过调用 this.setState() 来更新你的组件状态,这里调用更新状态是安全的,并不会触发额外的 render() 调用。如下:


     
     
  1. componentWillReceiveProps: function(nextProps) {
  2. this.setState({
  3. likesIncreasing: nextProps.likeCount > this.props.likeCount
  4. });
  5. }

shouldComponentUpdate

当组件接收到新的属性和状态改变的话,都会触发调用 shouldComponentUpdate(...),函数原型如下:


     
     
  1. boolean shouldComponentUpdate(
  2. object nextProps, object nextState
  3. )

输入参数 nextProps 和上面的 componentWillReceiveProps 函数一样,nextState 表示组件即将更新的状态值。这个函数的返回值决定是否需要更新组件,如果 true 表示需要更新,继续走后面的更新流程。否者,则不更新,直接进入等待状态。

默认情况下,这个函数永远返回 true 用来保证数据变化的时候 UI 能够同步更新。在大型项目中,你可以自己重载这个函数,通过检查变化前后属性和状态,来决定 UI 是否需要更新,能有效提高应用性能。

componentWillUpdate

如果组件状态或者属性改变,并且上面的 shouldComponentUpdate(...) 返回为 true,就会开始准更新组件,并调用 componentWillUpdate(),其函数原型如下:


     
     
  1. void componentWillUpdate(
  2. object nextProps, object nextState
  3. )

输入参数与 shouldComponentUpdate 一样,在这个回调中,可以做一些在更新界面之前要做的事情。需要特别注意的是,在这个函数里面,你就不能使用 this.setState 来修改状态。这个函数调用之后,就会把 nextProps 和 nextState 分别设置到 this.props和 this.state 中。紧接着这个函数,就会调用 render() 来更新界面了。

componentDidUpdate

调用了 render() 更新完成界面之后,会调用 componentDidUpdate() 来得到通知,其函数原型如下:


     
     
  1. void componentDidUpdate(
  2. object prevProps, object prevState
  3. )

因为到这里已经完成了属性和状态的更新了,此函数的输入参数变成了 prevProps 和 prevState

componentWillUnmount

当组件要被从界面上移除的时候,就会调用 componentWillUnmount(),其函数原型如下:


     
     
  1. void componentWillUnmount()

在这个函数中,可以做一些组件相关的清理工作,例如取消计时器、网络请求等。


生命周期回调函数学习笔记小例(ES6)


学习就要与时俱进,试着接受和学习新东西,下面的例子都是用ES6写的。


1、设置默认属性


代码:


     
     
  1. class RNHybrid extends Component {
  2.   
  3.   render() {  
  4.       return(  
  5.         <View style={styles.container}> 
  6.           <Text style={{padding:10, fontSize:42}}>
  7.                 {this.props.name}
  8.           </Text>
  9.         </View>  
  10.       );  
  11.    }
  12. }
  13. RNHybrid.defaultProps = {
  14.   name: ‘Mary’,
  15. };


效果:





ES5和ES6写法对比:

ES6


      
      
  1. class Greeting extends React . Component {
  2. // …
  3. }
  4. Greeting . defaultProps = {
  5. name : ’Mary’
  6. };


ES5


      
      
  1. var Greeting = createReactClass ({
  2. getDefaultProps : function () {
  3. return {
  4. name : ’Mary’
  5. };
  6. },
  7. // …
  8. });



总结:
          props相当于iOS 里的属性,但是这个属性只是readonly。我们可以通过this.props来读取属性。


2、设置状态


   由图片我们知道,当我们修改状态的时候,会从新调用render函数重新渲染页面,所以一些和界面有关的动态变量需要设置成状态。

   如上一篇的例子,我在从新copy一遍:

看下效果:





代码:(生命周期现在还没有说我也是偏面的了解,以后会系统的学习,现在先不介绍)

[javascript]  view plain  copy




  1. constructor(props) {  

  2.         super(props);  

  3.         //设置当前状态是text  初始值为空  

  4.         this.state = {text: };  

  5.     }  

  6.   

  7.   render() {    

  8.       return(    

  9.         <View style={styles.container}>   

  10.           <TextInput style={styles.TextInputStyles}   

  11.               onChangeText={(Text)=>{  

  12.                 this.setState({text:Text});  

  13.               }}  

  14.           />   

  15.           <Text style={{padding:10, fontSize:42}}>  

  16.                 {this.state.text}  

  17.           </Text>  

  18.         </View>    

  19.       );    

  20.    }  



ES5和ES6写法对比:

ES6 


       
       
  1. class myClass extends React . Component {
  2. constructor ( props ) {
  3. super ( props );
  1. this.state = {text:''};
  2. }
  3. // ...
  4. }


ES5


       
       
  1. var myClass = createReactClass({
  2. getInitialState : function () {
  3. return { text : };
  4. },
  5. // …
  6. });


ES5和ES6还有一个不同的地方,如果调用事件函数需要bind绑定

例如:


      
      
  1. class RNHybrid extends Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = { age: this.props.age};
  5. }
  6. handleClick() {
  7. alert( this.state.age);
  8. }
  9. render() {
  10. return(
  11. <View style={styles.container}>
  12. <Text style={{padding:10, fontSize:42}} onPress={this.handleClick}>
  13. {this.props.name}
  14. </Text>
  15. </View>
  16. );
  17. }
  18. }

这样写你点击的时候将会报错:



你需要将函数绑定:

1.可以在构造函数里绑定


      
      
  1. constructor(props) {
  2. super(props);
  3. this.state = { age: this.props.age};
  4. this.handleClick = this.handleClick.bind( this);
  5. }

2.还可以在调用的时候绑定


      
      
  1. <Text style={{ padding: 10, fontSize: 42}} onPress={ this.handleClick.bind( this)}>
  2. { this.props.name}
  3. < /Text>


3、其他生命周期函数验证


代码:


      
      
  1. import React, { Component } from ‘react’;
  2. import {
  3. AppRegistry,
  4. StyleSheet,
  5. View,
  6. Text,
  7. TextInput,
  8. } from ‘react-native’;
  9. var nowTime = new Date();
  10. var showText;
  11. class RNHybrid extends Component {
  12. constructor(props) {
  13. super(props);
  14. console.log( ‘state:’+nowTime);
  15. showText = ‘state:’+nowTime+ ‘\r\r’;
  16. //设置当前状态是text 初始值为空
  17. this.state = { text: };
  18. }
  19. componentWillMount(){
  20. console.log( ‘componentWillMount:’+nowTime);
  21. showText = showText+ ‘componentWillMount:’+nowTime+ ‘\r\r’;
  22. }
  23. componentDidMount(){
  24. console.log( ‘componentDidMount:’+nowTime);
  25. showText = showText+ ‘componentDidMount:’+nowTime+ ‘\r\r’;
  26. alert(showText);
  27. }
  28. shouldComponentUpdate(){
  29. console.log( ‘shouldComponentUpdate:’+nowTime);
  30. showText = showText+ ‘shouldComponentUpdate:’+nowTime+ ‘\r\r’;
  31. return true;
  32. }
  33. componentWillUpdate(){
  34. console.log( ‘componentWillUpdate:’+nowTime);
  35. showText = showText+ ‘componentWillUpdate:’+nowTime+ ‘\r\r’;
  36. }
  37. componentDidUpdate(){
  38. console.log( ‘componentDidUpdate:’+nowTime);
  39. showText = showText+ ‘componentDidUpdate:’+nowTime+ ‘\r\r’;
  40. }
  41. componentWillUnmount(){
  42. console.log( ‘componentWillUnmount:’+nowTime);
  43. showText = showText+ ‘componentWillUnmount:’+nowTime+ ‘\r\r’;
  44. }
  45. render() {
  46. return(
  47. <View style={styles.container}>
  48. <TextInput style={styles.TextInputStyles}
  49. onChangeText= {(Text)=>{
  50. this.setState({text:Text});
  51. }}
  52. />
  53. <Text style={{marginTop:10,padding:10, fontSize:15,borderColor:gray‘,borderWidth:1}}>
  54. {showText}
  55. </Text>
  56. </View>
  57. );
  58. }
  59. }
  60. RNHybrid.defaultProps = {
  61. name: ‘Mary’,
  62. age:’18’,
  63. };
  64. const styles = StyleSheet.create({
  65. container:{
  66. marginTop:100,
  67. flexDirection:’row’,
  68. flexWrap:’wrap’,
  69. justifyContent:’space-around’,
  70. },
  71. TextInputStyles:{
  72. width:200,
  73. height:60,
  74. borderWidth:2,
  75. borderColor:’red’,
  76. },
  77. });
  78. AppRegistry.registerComponent(‘RNHybrid’, () => RNHybrid);


效果:




分析:

    当加载时候,按照 构造函数-> componentWillMount -> render->componentDidMount 这个顺序来的。
     细心的人可能会发现,界面上并没有显示componentDidMount,是因为执行了这个函数并没有重新render。
    当你输入的时候改变state就按照图上左下角部分进行。重新render的时候,就会看到componentDidMount出现。

    验证图上的分析是合理的,我们也放心了。

前言:

这篇主要学习RN的生命周期,在开发中如果掌握了并熟练的运用生命周期函数的话,往往开发能事半功倍。

React Native生命周期简介





如图,可以把组件生命周期大致分为三个阶段:

  • 第一阶段:是组件第一次绘制阶段,如图中的上面虚线框内,在这里完成了组件的加载和初始化;
  • 第二阶段:是组件在运行和交互阶段,如图中左下角虚线框,这个阶段组件可以处理用户交互,或者接收事件更新界面;
  • 第三阶段:是组件卸载消亡的阶段,如图中右下角的虚线框中,这里做一些组件的清理工作。

生命周期回调函数(ES5写法)

下面来详细介绍生命周期中的各回调函数,先说下和上图对应的ES5写法。

getDefaultProps

在组件创建之前,会先调用 getDefaultProps(),这是全局调用一次,严格地来说,这不是组件的生命周期的一部分。在组件被创建并加载候,首先调用 getInitialState(),来初始化组件的状态。

componentWillMount

然后,准备加载组件,会调用 componentWillMount(),其原型如下:


   
   
  1. void componentWillMount()

这个函数调用时机是在组件创建,并初始化了状态之后,在第一次绘制 render() 之前。可以在这里做一些业务初始化操作,也可以设置组件状态。这个函数在整个生命周期中只被调用一次。

componentDidMount

在组件第一次绘制之后,会调用 componentDidMount(),通知组件已经加载完成。函数原型如下:


   
   
  1. void componentDidMount()

这个函数调用的时候,其虚拟 DOM 已经构建完成,你可以在这个函数开始获取其中的元素或者子组件了。需要注意的是,RN 框架是先调用子组件的 componentDidMount(),然后调用父组件的函数。从这个函数开始,就可以和 JS 其他框架交互了,例如设置计时 setTimeout 或者 setInterval,或者发起网络请求。这个函数也是只被调用一次。这个函数之后,就进入了稳定运行状态,等待事件触发。

componentWillReceiveProps

如果组件收到新的属性(props),就会调用 componentWillReceiveProps(),其原型如下:


   
   
  1. void componentWillReceiveProps(
  2. object nextProps
  3. )

输入参数 nextProps 是即将被设置的属性,旧的属性还是可以通过 this.props 来获取。在这个回调函数里面,你可以根据属性的变化,通过调用 this.setState() 来更新你的组件状态,这里调用更新状态是安全的,并不会触发额外的 render() 调用。如下:


   
   
  1. componentWillReceiveProps: function(nextProps) {
  2. this.setState({
  3. likesIncreasing: nextProps.likeCount > this.props.likeCount
  4. });
  5. }

shouldComponentUpdate

当组件接收到新的属性和状态改变的话,都会触发调用 shouldComponentUpdate(...),函数原型如下:


   
   
  1. boolean shouldComponentUpdate(
  2. object nextProps, object nextState
  3. )

输入参数 nextProps 和上面的 componentWillReceiveProps 函数一样,nextState 表示组件即将更新的状态值。这个函数的返回值决定是否需要更新组件,如果 true 表示需要更新,继续走后面的更新流程。否者,则不更新,直接进入等待状态。

默认情况下,这个函数永远返回 true 用来保证数据变化的时候 UI 能够同步更新。在大型项目中,你可以自己重载这个函数,通过检查变化前后属性和状态,来决定 UI 是否需要更新,能有效提高应用性能。

componentWillUpdate

如果组件状态或者属性改变,并且上面的 shouldComponentUpdate(...) 返回为 true,就会开始准更新组件,并调用 componentWillUpdate(),其函数原型如下:


   
   
  1. void componentWillUpdate(
  2. object nextProps, object nextState
  3. )

输入参数与 shouldComponentUpdate 一样,在这个回调中,可以做一些在更新界面之前要做的事情。需要特别注意的是,在这个函数里面,你就不能使用 this.setState 来修改状态。这个函数调用之后,就会把 nextProps 和 nextState 分别设置到 this.props和 this.state 中。紧接着这个函数,就会调用 render() 来更新界面了。

componentDidUpdate

调用了 render() 更新完成界面之后,会调用 componentDidUpdate() 来得到通知,其函数原型如下:


   
   
  1. void componentDidUpdate(
  2. object prevProps, object prevState
  3. )

因为到这里已经完成了属性和状态的更新了,此函数的输入参数变成了 prevProps 和 prevState

componentWillUnmount

当组件要被从界面上移除的时候,就会调用 componentWillUnmount(),其函数原型如下:


   
   
  1. void componentWillUnmount()

在这个函数中,可以做一些组件相关的清理工作,例如取消计时器、网络请求等。


生命周期回调函数学习笔记小例(ES6)


学习就要与时俱进,试着接受和学习新东西,下面的例子都是用ES6写的。


1、设置默认属性


代码:


   
   
  1. class RNHybrid extends Component {
  2.   
  3.   render() {  
  4.       return(  
  5.         <View style={styles.container}> 
  6.           <Text style={{padding:10, fontSize:42}}>
  7.                 {this.props.name}
  8.           </Text>
  9.         </View>  
  10.       );  
  11.    }
  12. }
  13. RNHybrid.defaultProps = {
  14.   name: ‘Mary’,
  15. };


效果:





ES5和ES6写法对比:

ES6


    
    
  1. class Greeting extends React . Component {
  2. // …
  3. }
  4. Greeting . defaultProps = {
  5. name : ’Mary’
  6. };


ES5


    
    
  1. var Greeting = createReactClass ({
  2. getDefaultProps : function () {
  3. return {
  4. name : ’Mary’
  5. };
  6. },
  7. // …
  8. });



总结:
          props相当于iOS 里的属性,但是这个属性只是readonly。我们可以通过this.props来读取属性。


2、设置状态


   由图片我们知道,当我们修改状态的时候,会从新调用render函数重新渲染页面,所以一些和界面有关的动态变量需要设置成状态。

   如上一篇的例子,我在从新copy一遍:

看下效果:





代码:(生命周期现在还没有说我也是偏面的了解,以后会系统的学习,现在先不介绍)

[javascript]  view plain  copy




  1. constructor(props) {  

  2.         super(props);  

  3.         //设置当前状态是text  初始值为空  

  4.         this.state = {text: };  

  5.     }  

  6.   

  7.   render() {    

  8.       return(    

  9.         <View style={styles.container}>   

  10.           <TextInput style={styles.TextInputStyles}   

  11.               onChangeText={(Text)=>{  

  12.                 this.setState({text:Text});  

  13.               }}  

  14.           />   

  15.           <Text style={{padding:10, fontSize:42}}>  

  16.                 {this.state.text}  

  17.           </Text>  

  18.         </View>    

  19.       );    

  20.    }  



ES5和ES6写法对比:

ES6 


     
     
  1. class myClass extends React . Component {
  2. constructor ( props ) {
  3. super ( props );
  1. this.state = {text:''};
  2. }
  3. // ...
  4. }


ES5


     
     
  1. var myClass = createReactClass({
  2. getInitialState : function () {
  3. return { text : };
  4. },
  5. // …
  6. });


ES5和ES6还有一个不同的地方,如果调用事件函数需要bind绑定

例如:


    
    
  1. class RNHybrid extends Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = { age: this.props.age};
  5. }
  6. handleClick() {
  7. alert( this.state.age);
  8. }
  9. render() {
  10. return(
  11. <View style={styles.container}>
  12. <Text style={{padding:10, fontSize:42}} onPress={this.handleClick}>
  13. {this.props.name}
  14. </Text>
  15. </View>
  16. );
  17. }
  18. }

这样写你点击的时候将会报错:



你需要将函数绑定:

1.可以在构造函数里绑定


    
    
  1. constructor(props) {
  2. super(props);
  3. this.state = { age: this.props.age};
  4. this.handleClick = this.handleClick.bind( this);
  5. }

2.还可以在调用的时候绑定


    
    
  1. <Text style={{ padding: 10, fontSize: 42}} onPress={ this.handleClick.bind( this)}>
  2. { this.props.name}
  3. < /Text>


3、其他生命周期函数验证


代码:


    
    
  1. import React, { Component } from ‘react’;
  2. import {
  3. AppRegistry,
  4. StyleSheet,
  5. View,
  6. Text,
  7. TextInput,
  8. } from ‘react-native’;
  9. var nowTime = new Date();
  10. var showText;
  11. class RNHybrid extends Component {
  12. constructor(props) {
  13. super(props);
  14. console.log( ‘state:’+nowTime);
  15. showText = ‘state:’+nowTime+ ‘\r\r’;
  16. //设置当前状态是text 初始值为空
  17. this.state = { text: };
  18. }
  19. componentWillMount(){
  20. console.log( ‘componentWillMount:’+nowTime);
  21. showText = showText+ ‘componentWillMount:’+nowTime+ ‘\r\r’;
  22. }
  23. componentDidMount(){
  24. console.log( ‘componentDidMount:’+nowTime);
  25. showText = showText+ ‘componentDidMount:’+nowTime+ ‘\r\r’;
  26. alert(showText);
  27. }
  28. shouldComponentUpdate(){
  29. console.log( ‘shouldComponentUpdate:’+nowTime);
  30. showText = showText+ ‘shouldComponentUpdate:’+nowTime+ ‘\r\r’;
  31. return true;
  32. }
  33. componentWillUpdate(){
  34. console.log( ‘componentWillUpdate:’+nowTime);
  35. showText = showText+ ‘componentWillUpdate:’+nowTime+ ‘\r\r’;
  36. }
  37. componentDidUpdate(){
  38. console.log( ‘componentDidUpdate:’+nowTime);
  39. showText = showText+ ‘componentDidUpdate:’+nowTime+ ‘\r\r’;
  40. }
  41. componentWillUnmount(){
  42. console.log( ‘componentWillUnmount:’+nowTime);
  43. showText = showText+ ‘componentWillUnmount:’+nowTime+ ‘\r\r’;
  44. }
  45. render() {
  46. return(
  47. <View style={styles.container}>
  48. <TextInput style={styles.TextInputStyles}
  49. onChangeText= {(Text)=>{
  50. this.setState({text:Text});
  51. }}
  52. />
  53. <Text style={{marginTop:10,padding:10, fontSize:15,borderColor:gray‘,borderWidth:1}}>
  54. {showText}
  55. </Text>
  56. </View>
  57. );
  58. }
  59. }
  60. RNHybrid.defaultProps = {
  61. name: ‘Mary’,
  62. age:’18’,
  63. };
  64. const styles = StyleSheet.create({
  65. container:{
  66. marginTop:100,
  67. flexDirection:’row’,
  68. flexWrap:’wrap’,
  69. justifyContent:’space-around’,
  70. },
  71. TextInputStyles:{
  72. width:200,
  73. height:60,
  74. borderWidth:2,
  75. borderColor:’red’,
  76. },
  77. });
  78. AppRegistry.registerComponent(‘RNHybrid’, () => RNHybrid);


效果:




分析:

    当加载时候,按照 构造函数-> componentWillMount -> render->componentDidMount 这个顺序来的。
     细心的人可能会发现,界面上并没有显示componentDidMount,是因为执行了这个函数并没有重新render。
    当你输入的时候改变state就按照图上左下角部分进行。重新render的时候,就会看到componentDidMount出现。

    验证图上的分析是合理的,我们也放心了。

猜你喜欢

转载自blog.csdn.net/qq_34983989/article/details/81082180