React Native 生命週期

前言:

         在面向對象編程中,任何對象的存在都會存在生命週期。類似我們iOS 的View,就會有LoadView,ViewWillAppear,ViewDidLoad等等生命週期。RN也不例外,這篇主要學習RN的生命週期,在開發中如果掌握了並熟練的運用生命週期函數的話,往往開發能事半功倍。

React Native生命週期簡介

如圖,可以把組件生命週期大致分爲三個階段:

  • 第一階段:是組件第一次繪製階段,如圖中的上面虛線框內,在這裏完成了組件的加載和初始化;
  • 第二階段:是組件在運行和交互階段,如圖中左下角虛線框,這個階段組件可以處理用戶交互,或者接收事件更新界面;
  • 第三階段:是組件卸載消亡的階段,如圖中右下角的虛線框中,這裏做一些組件的清理工作。

生命週期回調函數(ES5寫法)

下面來詳細介紹生命週期中的各回調函數,先說下和上圖對應的ES5寫法。

getDefaultProps

在組件創建之前,會先調用 getDefaultProps(),這是全局調用一次,嚴格地來說,這不是組件的生命週期的一部分。在組件被創建並加載候,首先調用 getInitialState(),來初始化組件的狀態。

componentWillMount

然後,準備加載組件,會調用 componentWillMount(),其原型如下:

void componentWillMount()  

這個函數調用時機是在組件創建,並初始化了狀態之後,在第一次繪製 render() 之前。可以在這裏做一些業務初始化操作,也可以設置組件狀態。這個函數在整個生命週期中只被調用一次。

componentDidMount

在組件第一次繪製之後,會調用 componentDidMount(),通知組件已經加載完成。函數原型如下:

void componentDidMount()  

這個函數調用的時候,其虛擬 DOM 已經構建完成,你可以在這個函數開始獲取其中的元素或者子組件了。需要注意的是,RN 框架是先調用子組件的 componentDidMount(),然後調用父組件的函數。從這個函數開始,就可以和 JS 其他框架交互了,例如設置計時 setTimeout 或者 setInterval,或者發起網絡請求。這個函數也是隻被調用一次。這個函數之後,就進入了穩定運行狀態,等待事件觸發。

componentWillReceiveProps

如果組件收到新的屬性(props),就會調用 componentWillReceiveProps(),其原型如下:

void componentWillReceiveProps(  
  object nextProps
)

輸入參數 nextProps 是即將被設置的屬性,舊的屬性還是可以通過 this.props 來獲取。在這個回調函數裏面,你可以根據屬性的變化,通過調用 this.setState() 來更新你的組件狀態,這裏調用更新狀態是安全的,並不會觸發額外的 render() 調用。如下:

componentWillReceiveProps: function(nextProps) {  
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

shouldComponentUpdate

當組件接收到新的屬性和狀態改變的話,都會觸發調用 shouldComponentUpdate(...),函數原型如下:

boolean shouldComponentUpdate(  
  object nextProps, object nextState
)

輸入參數 nextProps 和上面的 componentWillReceiveProps 函數一樣,nextState 表示組件即將更新的狀態值。這個函數的返回值決定是否需要更新組件,如果 true 表示需要更新,繼續走後面的更新流程。否者,則不更新,直接進入等待狀態。

默認情況下,這個函數永遠返回 true 用來保證數據變化的時候 UI 能夠同步更新。在大型項目中,你可以自己重載這個函數,通過檢查變化前後屬性和狀態,來決定 UI 是否需要更新,能有效提高應用性能。

componentWillUpdate

如果組件狀態或者屬性改變,並且上面的 shouldComponentUpdate(...) 返回爲 true,就會開始準更新組件,並調用 componentWillUpdate(),其函數原型如下:

void componentWillUpdate(  
  object nextProps, object nextState
)

輸入參數與 shouldComponentUpdate 一樣,在這個回調中,可以做一些在更新界面之前要做的事情。需要特別注意的是,在這個函數裏面,你就不能使用 this.setState 來修改狀態。這個函數調用之後,就會把 nextProps 和 nextState 分別設置到 this.props和 this.state 中。緊接着這個函數,就會調用 render() 來更新界面了。

componentDidUpdate

調用了 render() 更新完成界面之後,會調用 componentDidUpdate() 來得到通知,其函數原型如下:

void componentDidUpdate(  
  object prevProps, object prevState
)

因爲到這裏已經完成了屬性和狀態的更新了,此函數的輸入參數變成了 prevProps 和 prevState

componentWillUnmount

當組件要被從界面上移除的時候,就會調用 componentWillUnmount(),其函數原型如下:

void componentWillUnmount()  

在這個函數中,可以做一些組件相關的清理工作,例如取消計時器、網絡請求等。

生命週期回調函數學習筆記小例(ES6)

學習就要與時俱進,試着接受和學習新東西,下面的例子都是用ES6寫的。

1、設置默認屬性

代碼:

 class RNHybrid extends Component {
  
  render() {  
      return(  
        <View style={styles.container}> 
          <Text style={{padding:10, fontSize:42}}>
                {this.props.name}
          </Text>
        </View>  
      );  
   }
}


RNHybrid.defaultProps = {
  name: 'Mary',
};

效果:

ES5和ES6寫法對比:

ES6

class Greeting extends React.Component {
  // ...
}

Greeting.defaultProps = {
  name: 'Mary'
};

ES5

var Greeting = createReactClass({
  getDefaultProps: function() {
    return {
      name: 'Mary'
    };
  },

  // ...

});

總結:

          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 

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

ES5

var myClass = createReactClass({
  getInitialState: function() {
    return {text: ''};
  },
  // ...
});

 

ES5和ES6還有一個不同的地方,如果調用事件函數需要bind綁定

例如:

class RNHybrid extends Component {
  

  constructor(props) {
        super(props);
        this.state = {age:this.props.age};
    }

 handleClick() {
    alert(this.state.age);
  }

  render() {  
      return(  
        <View style={styles.container}> 
          <Text style={{padding:10, fontSize:42}} onPress={this.handleClick}>
                {this.props.name}
          </Text>
        </View>  
      );  
   }
}

這樣寫你點擊的時候將會報錯:

你需要將函數綁定:

1.可以在構造函數裏綁定

 constructor(props) {
        super(props);
        this.state = {age:this.props.age};
        this.handleClick = this.handleClick.bind(this);
    }

2.還可以在調用的時候綁定

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

3、其他生命週期函數驗證

代碼:

import React, { Component } from 'react';
import {
   AppRegistry,
  StyleSheet,
  View,
  Text,
  TextInput,
} from 'react-native';

var  nowTime = new Date();
var  showText;

class RNHybrid extends Component {
  
  constructor(props) {  
        super(props);  
        console.log('state:'+nowTime);
        showText = 'state:'+nowTime+'\r\r';   
        //設置當前狀態是text  初始值爲空  
        this.state = {text: ''};  
  }


  componentWillMount(){
    console.log('componentWillMount:'+nowTime);
    showText = showText+'componentWillMount:'+nowTime+'\r\r';   
  } 

  componentDidMount(){
    console.log('componentDidMount:'+nowTime);
    showText = showText+'componentDidMount:'+nowTime+'\r\r';   
    alert(showText);
  } 

  shouldComponentUpdate(){
    console.log('shouldComponentUpdate:'+nowTime);
    showText = showText+'shouldComponentUpdate:'+nowTime+'\r\r';   
    return true;
  } 
   
  componentWillUpdate(){
    console.log('componentWillUpdate:'+nowTime);
    showText = showText+'componentWillUpdate:'+nowTime+'\r\r';       
  } 

  componentDidUpdate(){
    console.log('componentDidUpdate:'+nowTime);
    showText = showText+'componentDidUpdate:'+nowTime+'\r\r';       
  } 

  componentWillUnmount(){
    console.log('componentWillUnmount:'+nowTime);
    showText = showText+'componentWillUnmount:'+nowTime+'\r\r';       
  }

  render() {    
      return(    
        <View style={styles.container}>   
          <TextInput style={styles.TextInputStyles}   
              onChangeText={(Text)=>{  
                this.setState({text:Text});  
              }}  
          />   
          <Text style={{marginTop:10,padding:10, fontSize:15,borderColor:'gray',borderWidth:1}}>  
                {showText}  
          </Text>  
        </View>    
      );    
   }  
}

RNHybrid.defaultProps = {
  name: 'Mary',
  age:'18',
};


const styles = StyleSheet.create({
   container:{
   		marginTop:100,
   		flexDirection:'row',
      flexWrap:'wrap',
      justifyContent:'space-around',
   },
   TextInputStyles:{
      width:200,
      height:60,
      borderWidth:2,
      borderColor:'red',
   },
});

AppRegistry.registerComponent('RNHybrid', () => RNHybrid);

效果:

分析:

當加載時候,按照 構造函數-> componentWillMount -> render->componentDidMount 這個順序來的。

     細心的人可能會發現,界面上並沒有顯示componentDidMount,是因爲執行了這個函數並沒有重新render。

    當你輸入的時候改變state就按照圖上左下角部分進行。重新render的時候,就會看到componentDidMount出現。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章