React Native生命週期主要分爲三大階段:實例化階段(圖中上框部分),存在階段(圖中左框部分),銷燬階段(圖中右框部分)。javascript
如圖:java
下面簡單講解一下三大階段中各自的函數:react
實例化階段:git
在平常開發中,最爲經常使用的就是實例化階段,由於該階段是組件的構建,展現階段。github
getDefaultProps: react-native
該函數用於初始化一些默認的屬性,開發中,一般將一些固定不變的值放在該函數內進行初始化,好比url。能夠利用this.props.XXX 來獲取該屬性值。因爲被初始化後,之後就不會再調用getDefaultProps函數,因此不能對props修改,也就是pros是隻讀屬性的。數組
getInitialState:網絡
該函數用於對組件的一些狀態進行初始化,該狀態是隨時變化的(也就是說該函數會被屢次調用),好比ListView的datasource,rowData等等,一樣的,能夠經過this.state.XXX獲取該屬性值,同時能夠對該值進行修改,經過this.setState修改,如:
函數
this.setState({ age:11, name:'少停' });
componentWillMount: flex
該函數相似於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);
完成源碼下載: