React Native之生命周期


 

React Native生命周期主要分為三大階段:實例化階段(圖中上框部分),存在階段(圖中左框部分),銷毀階段(圖中右框部分)。

如圖:

下面簡單講解一下三大階段中各自的函數:

實例化階段:

在日常開發中,最為常用的就是實例化階段,因為該階段是組件的構建,展示階段。

getDefaultProps: 

      該函數用於初始化一些默認的屬性,開發中,通常將一些固定不變的值放在該函數內進行初始化,比如url。可以利用this.props.XXX 來獲取該屬性值。由於被初始化后,以后就不會再調用getDefaultProps函數,所以不能對props修改,也就是pros是只讀屬性的。

getInitialState:

  該函數用於對組件的一些狀態進行初始化,該狀態是隨時變化的(也就是說該函數會被多次調用),比如ListView的datasource,rowData等等,同樣的,可以通過this.state.XXX獲取該屬性值,同時可以對該值進行修改,通過this.setState修改,如:

this.setState({
    age:11,
    name:'少停'
});

componentWillMount: 

  該函數類似於iOS中的VillWillAppear,在組件即將加載在視圖上調用。

render: 

  該函數組件必有的,通過返回JSX或其他組件來構成DOM,換言之,就是組件的核心渲染過程。

componentDidMount:

  在執行完render函數之后,該函數被執行,我們通常可以在該函數當中做一些復雜操作,如網絡請求。

存在階段:

componentWillReceiveProps:

  組件將要修改props或者state

 shouldComponentUpdate:

  常用於優化

componentWillUpdate:

  組件更新時調用

componentDidUpdate:

  組件更新完畢時調用

銷毀階段:

componentWillUnmount:

  通常做一些清理內容  

 

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * 周少停 生命周期:實例化階段.存在階段.銷毀階段
 * 2016-09-19
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';
//ES5寫法 ES5寫法和ES6稍有不同
var LifeDate = React.createClass({  
  getDefaultProps(){    //初始化一些不可以修改的值,初始化完畢后將不會再次調用,可以通過this.props來獲取初始化后的值,不可以修改
    return{
        age:18 //永遠18
    };
  },
  getInitialState(){     //初始化一些可以修改的值,會多次調用,可以通過this.state來獲取值,通過this.setState來修改修改值
    return {
      isGoodPerson:true,
      content: '我是什么人'
    };
  },
  componentWillMount(){
    return{
                        //相當於iOS中viewWillAppear
    };
  },
  componentDidMount(){
    return{
                        //相當於iOS中的viewDidLoad 可以在這里做一些復雜操作,如網絡請求數據
    };
  },
  render() {
    return (
      <View ref="topView" style={styles.container}>
        <TouchableOpacity onPress = {() =>this.dealWithState(this.state.isGoodPerson)}>
          <View style={styles.innerViewStyle}>
            <Text>{this.state.content}</Text>
            <Text>{this.props.age}</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  },
  dealWithState: function(data:Boolean){
    var isGoodPerson,content;
    if(data){
      isGoodPerson = false,
      content = '我是大好人'
    }else{
      isGoodPerson = true,
      content = '我是壞淫'
    }
    //更新狀態機
    this.setState({
      isGoodPerson: isGoodPerson,
      content: content
    });
    //拿到View
    this.refs.topView
  }  
});
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF'
  },
  innerViewStyle: {
    backgroundColor: 'red'
  }
});

AppRegistry.registerComponent('Project', () => LifeDate);

完成源碼下載:

https://github.com/pheromone/React-Native-1  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM