Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

React Native 組件的生命週期:十個回調到底誰先誰後

編輯:關於 Android 程式設計

和 Android 一樣,React 的組件也有完整的生命週期。Android React Native 組件的生命週期可以概括成下面這張圖。

大體可分為三個階段:

  • 首次繪製階段(圖中上方虛線框):完成組件的加載與初始化;
  • 運行與交互階段(左下虛線框):處理用戶交互,或接收事件更新界面;
  • 卸載消亡階段(右下虛線框):做一些清理工作。

生命週期回調函數共 10 個。先看一個把所有回調都打印出來的樣例:

'use strict';

var React = require('react-native');
var { AppRegistry, StyleSheet, View, Text } = React;

var AwesomeProject = React.createClass({

    // 組件類創建時調用一次,返回值會被緩存
    getDefaultProps: function () {
        console.log("getDefaultProps");
        return null;
    },

    // 掛載前調用一次,返回值作為 this.state 的初始值
    getInitialState: function () {
        console.log("getInitialState");
        return null; // 必須有返回值,可以是 null 或對象
    },

    // 即將渲染
    componentWillMount: function () {
        console.log("componentWillmount");
    },

    // 渲染視圖,返回 null 或 false 表示不渲染任何內容
    render: function () {
        console.log("render");
        return (
            <View></View>
        );
    },

    // 渲染完成後,適合在這裡做異步加載
    componentDidMount: function () {
        console.log("componentDidMount");
        this.loadDataToSetState();
    },

    // 接收到新屬性;首次渲染時不會觸發
    componentWillReceiveProps: function (nextProps) {
        console.log("componentWillReceiveProps");
    },

    // 決定是否需要重新渲染,返回 false 可跳過後續更新
    shouldComponentUpdate: function (nextProps, nextState) {
        console.log("shouldComponentUpdate");
        return true;
    },

    // 即將更新
    componentWillUpdate: function (nextProps, nextState) {
        console.log("componentWillUpdate");
    },

    // 更新完成
    componentDidUpdate: function (prevProps, prevState) {
        console.log("conponentDidUpdate");
    },

    // 銷毀前做清理
    componentWillUnmount: function () {
        console.log("componentWillUnmount");
    },

    loadDataToSetState: function () {
        console.log("loadDataToSetState");
        this.setState({ name: "RN" });
    }
});

var styles = StyleSheet.create({});

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

輸出順序如下:

getDefaultProps
getInitialState
componentWillmount
render
componentDidMount
loadDataToSetState
shouldComponentUpdate
componentWillUpdate
render
conponentDidUpdate
componentWillUnmount

解讀一下:componentDidMount 中調用了 loadDataToSetState,其中通過 setState 修改了 state,於是觸發 shouldComponentUpdate;返回 true 後依次走 componentWillUpdate、render、componentDidUpdate。最後按返回鍵退出應用,觸發銷毀回調 componentWillUnmount。

值得記住的一點:setState 是異步的,它不會立即修改 this.state,而是把更新排入隊列。這也是為什麼不能在 componentWillUpdate 裡再調 setState——會造成無限循環。

componentWillReceiveProps 的觸發時機

這個回調只在 props 變化時觸發,場景是「父組件改變了子組件的屬性」。先定義一個子組件:

var Name = React.createClass({
    getDefaultProps: function () { console.log("Name getDefaultProps"); return null; },
    getInitialState: function () { console.log("Name getInitialState"); return null; },
    componentWillMount: function () { console.log("Name componentWillmount"); },
    render: function () {
        console.log("Name render");
        return (
            <Text>Hello, {this.props.name ? this.props.name : "None!"}</Text>
        );
    },
    componentDidMount: function () { console.log("Name componentDidMount"); },
    componentWillReceiveProps: function (nextProps) {
        console.log("Name componentWillReceiveProps");
        console.log(nextProps);
    },
    shouldComponentUpdate: function (nextProps, nextState) {
        console.log("Name shouldComponentUpdate");
        return true;
    },
    componentWillUpdate: function (nextProps, nextState) {
        console.log("Name componentWillUpdate");
    },
    componentDidUpdate: function (prevProps, prevState) {
        console.log("Name conponentDidUpdate");
    },
    componentWillUnmount: function () { console.log("Name componentWillUnmount"); }
});

再定義父組件,在 render 中使用子組件並傳入 name 屬性:

var Parent = React.createClass({
    render: function () {
        return (
            <View>
                <Name name={this.state.name} />
            </View>
        );
    },
    getInitialState: function () {
        return { name: "a" };
    },
    componentDidMount: function () {
        this.setState({ name: "lizhangqu" }); // 掛載後改變 state
    }
});

界面中直接返回父組件:

var AwesomeProject = React.createClass({
    render: function () {
        return (
            <Parent></Parent>
        );
    }
});

父組件掛載完成後 setState 改了 state,render 重新執行,子組件的 name 屬性隨之變化,於是觸發 componentWillReceiveProps。完整輸出:

Name getDefaultProps
Name getInitialState
Name componentWillmount
Name render
Name componentDidMount
Name componentWillReceiveProps  Object {name: "lizhangqu"}
Name shouldComponentUpdate
Name componentWillUpdate
Name render
Name conponentDidUpdate
Name componentWillUnmount

對比一下就清楚了:getDefaultProps 與 getInitialState 只在首次創建時各執行一次,而 componentWillReceiveProps 是「後天」的——只有當父組件主動改了子組件的屬性才會出現。

調試方法

React Native 官網提供了 Chrome 下的調試插件 Chrome Developer Tools。安裝之後,在手機的開發者選項中開啟 debug js,就能在 Chrome 控制台裡看到日誌輸出與 JS 報錯信息了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved