ReactNative ☞ react-native 生命周期

一、单个组件的生命周期

ReactNative ☞ react-native 生命周期_第1张图片
单个React组件生命周期示意图

首先分析一下单个组件的生命周期,完成的代码如下:

//In App.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button} from 'react-native';

type Props = {};
export default class Home extends  Component{

    constructor(props) {
        super(props)
        console.log('Home-constructor');
       this.state = {
            title : '点我刷新'
        }
    }

   componentWillMount(): void {
        console.log('Home-componentWillMount');
    }

    componentWillUnmount(): void {
        console.log('Home-componentWillUnmount');
    }

    render() {
       console.log('Home-render');
        return (
            
              首页
              

运行结果如下:


ReactNative ☞ react-native 生命周期_第2张图片
运行结果

commend + D 打开Google Chrome浏览器,在浏览器中打印如下:


打印结果

点击刷新按钮,打印如下:


点击刷新按钮

二、多个组件的生命周期

为了模拟多个组件的生命周期,在上述代码的基础上,我们去掉Home组件的export default,重新定义一个名为Super的根视图组件

Super组件定义如下:

export default class Super extends Component {

    constructor(props) {
        super(props)
        console.log('Super-constructor');
    }

    componentWillMount(): void {
        console.log('Super-componentWillMount');
    }

    componentWillUnmount(): void {
        console.log('Super-componentWillUnmount');
    }

    render() {
        console.log('Super-render');
      return (
       //返回Home组件,此时Home作为子组件
        < Home />
     );
    }

    componentDidMount(): void {
        console.log('Super-componentDidMount');
    }

    shouldComponentUpdate(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean { console.log('Super-shouldComponentUpdate'); return ( true ) } componentWillReceiveProps(nextProps) { console.log('Super-componentWillReceiveProps') } componentWillUpdate(nextProps: Readonly

, nextState: Readonly, nextContext: any): void { console.log('Super-componentWillUpdate'); } componentDidUpdate(prevProps: Readonly

, prevState: Readonly, snapshot: SS): void { console.log('Super-componentDidUpdate'); } }

运行上述代码
打印如下:


ReactNative ☞ react-native 生命周期_第3张图片
多个组件运行结果

此时再点击Home组件上的按钮,打印如下


点击子组件按钮

你可能感兴趣的:(ReactNative ☞ react-native 生命周期)