react native学习笔记7——组件生命周期

每个组件都有自己的生命周期,在其生命周期内,组件经历了初始化-运行-销毁的过程。在运行阶段,每次状态(state)或属性(props)发生变化时,都有对应的组件方法将该变化通知给组件进行渲染刷新(关于state和props的介绍可以看上一节react native学习笔记6——Props和State)。下图是经典的组件生命周期图解(ES6),该图显示了组件在生命周期的各个时期系统调用的方法。

下面我们根据初始化-运行-销毁三个阶段逐步分析组件生命周期的过程。

初始化

初始化主要发生在创建组件的时候,在这个阶段中会获取组件的默认属性和初始化组件的状态,修改组件状态,渲染组件。在初始化的过程中,会按顺序调用下面4个函数:

constructor(props):构造函数,组件实例创建时调用,主要接收从父组件传递过来的props作为组件的初始属性,并初始化state。

在ES5中是属性props的获取和state的初始化是通过getDefaultPropsgetInitalState方法来实现

componentWillMount:准备加载组件,在constructor构造函数之后,render前调用,且只调用一次。可以在这里做一些业务初始化操作,也可以设置组件状态,通过setState方法修改state。

render:渲染组件,是一个组件中必须有的函数,render只允许返回一个最外层容器组件。

componentDidMount:在初始化阶段第一次执行render之后,组件被成功渲染出来以后立刻调用。一般在该函数中执行网络请求等操作。

运行中

初始化完成之后,组件将会进入到运行中状态,在该阶段中通常会由于与用户发生交互之后、网络请求结果返回、父组件有更新等情况导致组件需要重新渲染更新。运行中阶段可能会执行到如下5个函数:

componentWillReceiveProps(nextProps):当父组件有更新传入新的属性给子组件,子组件接收到新的props时,会触发该函数。新的props将会作为参数传递进来,可以用于更新 state 来响应 props 的改变。

boolean shouldComponentUpdate(object nextProps,object nextState):该函数决定是否需要更新组件,在接收到新的props或state时,将要渲染之前调用,返回 false表示不用重新渲染,返回true将进行渲染。用户可以通过相应的业务逻辑根据情况,对接收到的参数nextProps和nextState判断是否需要更新界面。

componentWillUpdate(object nextProps,object nextState) :如果前面的shouldComponentUpdate返回为true时调用该函数,在这个函数中可以处理在更新界面之前要做的准备工作。

注意:不能在该函数中更新state和props。

render:更新界面。

componentDidUpdate(object prevProps,object prevState):组件更新完成后立即调用,功能上类似于初始化阶段中的componentDidMount,该函数的参数是当前的props和state。

销毁

销毁阶段主要发生组件销亡的时候。

componentWillUnmount():组件被移除时调用,可在该函数中执行一些清理工作,如取消事件绑定,移除无用计时器。

日志跟踪理解组件生命周期

为了加深记忆,通过代码实例打印组件生命周期中的被执行的各个函数。
1.下面示例演示状态改变时生命周期中各函数的调用顺序:
LifecycleDemo.js

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

export default class Greeting extends Component {
    //初始化获取父组件的
    constructor(props) {
        super(props);
        console.log("getDefaultProps");
        this.state = {name: props.name};
        console.log("getInitialState");
    }

    // 在render之前调用
    componentWillMount(){
       console.log("componentWillMount");
    }

    componentWillUnMount(){
        console.log("componentWillUnMount");
    }
    componentWillUpdate(nextProps,nextState){
    console.log("componentWillUpdate");
    }
    componentDidUpdate(prevProps,prevState){
        console.log("componentDidUpdate");
    }
    componentWillReceiveProps(nextProps){
        console.log("componentWillReceiveProps");
    }
    shouldComponentUpdate(nextProps,nextState) {
        console.log("shouldComponentUpdate");
        return true;
    }

    render() {
        console.log("render");
        return (
            <View style={ {height:40,backgroundColor:"darkgray"}}> <Text>Hello {this.state.name} </Text> </View> ); } changeState(){ console.log("changeState"); this.setState({ name: "React Native" }); } componentDidMount() { console.log("componentDidMount"); this.changeState(); } }

该示例中,在componentDidMount中调用了changeState函数,该函数中通过了setState函数对state进行了设置,这时候就会回调shouldComponentUpdate,如果返回true,则会继续调用componentWillUpdate、render、conponentDidUpdate,之后按返回键退出应用,则会进行销毁操作,回调componentWillUnmount。日志输出为:


该示例的源码在:
https://github.com/mronion0603/ReactNativeExercise/blob/master/src/03_props_state_lifecycle/LifecycleDemo.js

2.对于props属性的改变而触发componentWillReceiveProps的情况稍微复杂点,由于组件自己不能修改自己的props属性(上一节有介绍),导致props改变只能通过父组件指定并向子层组件传递。因此这里我们添加一个父组件:
LifecycleDemo2.js

export default class LifecycleDemo2 extends Component {
    constructor(props) {
        super(props);
        this.state = {name: "onion"};
    }

    render() {
        return (
            <View > <Greeting name ={this.state.name} /> </View> ); } changeState(){ console.log("parent changeState"); this.setState({ name: "xiaofang" }); } componentDidMount() { console.log("parent componentDidMount"); this.changeState(); } }

在父组件的render中使用子组件,并将name属性传给子组件。

<Greeting name ={this.state.name} />

父组件中状态name的初始值是”onion”

constructor(props) {
        super(props);
        this.state = {name: "onion"};
    }

而当组件加载完成后,即render执行完成后,在componentDidMount中,通过setState函数设置父组件的state.name。

changeState(){
        console.log("changeState");
        this.setState({
            name: "xiaofang"
        });
    }

将父组件的state.name改为”xiaofang”,此时会触发父组件的render重新渲染,因而对子组件重新指定props.name的值。
子组件还是用上面Greeting的例子,不过将头部export default class Greeting extends Component改为class Greeting extends Component
另外为了简化流程,把子组件的componentDidMount中的changeState方法给去掉:

componentDidMount() {
      console.log("componentDidMount");
      //this.changeState();
}

由于父组件改变了子组件Greeting的props的属性,子组件中会调用componentWillReceiveProps函数。

其完整示例如下:

import React,} from 'react-native';

class Greeting extends Component {
    constructor(props) {
        super(props);
        this.state = {name: props.name};
        console.log("constructor");
    }

    componentWillMount(){
       // 在render之前调用
       console.log("componentWillMount");
    }

    componentWillUnMount(){
        console.log("componentWillUnMount");
    }
    componentWillUpdate(nextProps,prevState){
        console.log("componentDidUpdate");
    }
    componentWillReceiveProps(nextProps){
        this.setState({
            name: nextProps.name
        });
        console.log("componentWillReceiveProps");
    }
    shouldComponentUpdate(nextProps,nextState) {
        console.log("shouldComponentUpdate");
        return true;
    }

    render() {
        console.log("render");
        return (

            <View style={ {height:40,backgroundColor:"darkgray"}}> <Text>Hello {this.state.name} </Text> </View> ); } changeState(){ console.log("changeState"); this.setState({ name: "React Native" }); } componentDidMount() { console.log("componentDidMount"); //this.changeState(); } componentWillUnmount(){ console.log("componentWillUnmount"); } } export default class LifecycleDemo2 extends Component { constructor(props) { super(props); this.state = {name: "onion"}; } render() { return ( <View > <Greeting name ={this.state.name} /> </View> ); } changeState(){ console.log("parent changeState"); this.setState({ name: "xiaofang" }); } componentDidMount() { console.log("parent componentDidMount"); this.changeState(); } }

log日志输出结果如下:


该示例源码在:
https://github.com/mronion0603/ReactNativeExercise/blob/master/src/03_props_state_lifecycle/LifecycleDemo2.js

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如果组件之中有复用的代码,需要重新创建一个父类,父类中存储公共代码,返回子类,同时把公用属性...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例如我们的 setState 函数式同步执行的,我们的事件处理直接绑定在了 dom 元素上,这些都跟 re...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom 转为真实 dom 进行挂载。其实函数是组件和类组件也是在这个基础上包裹了一层,一个是调...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使用,可能是不了解。我公司的项目就没有使用,但是在很多三方库中都有使用。本小节我们来学习下如果使用该...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接触 react 就一直使用 mobx 库,上手简单不复杂。
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc 端可以使用分页进行渲染数限制,在移动端可以使用下拉加载更多。但是对于大量的列表渲染,特别像有实时数据...
本小节开始前,我们先答复下一个同学的问题。上一小节发布后,有小伙伴后台来信问到:‘小编你只讲了类组件中怎么使用 ref,那在函数式组件中怎么使用呢?’。确实我们...
上一小节我们了解了固定高度的滚动列表实现,因为是固定高度所以容器总高度和每个元素的 size、offset 很容易得到,这种场景也适合我们常见的大部分场景,例如...
上一小节我们处理了 setState 的批量更新机制,但是我们有两个遗漏点,一个是源码中的 setState 可以传入函数,同时 setState 可以传入第二...
我们知道 react 进行页面渲染或者刷新的时候,会从根节点到子节点全部执行一遍,即使子组件中没有状态的改变,也会执行。这就造成了性能不必要的浪费。之前我们了解...
在平时工作中的某些场景下,你可能想在整个组件树中传递数据,但却不想手动地通过 props 属性在每一层传递属性,contextAPI 应用而生。
楼主最近入职新单位了,恰好新单位使用的技术栈是 react,因为之前一直进行的是 vue2/vue3 和小程序开发,对于这些技术栈实现机制也有一些了解,最少面试...
我们上一节了了解了函数式组件和类组件的处理方式,本质就是处理基于 babel 处理后的 type 类型,最后还是要处理虚拟 dom。本小节我们学习下组件的更新机...
前面几节我们学习了解了 react 的渲染机制和生命周期,本节我们正式进入基本面试必考的核心地带 -- diff 算法,了解如何优化和复用 dom 操作的,还有...
我们在之前已经学习过 react 生命周期,但是在 16 版本中 will 类的生命周期进行了废除,虽然依然可以用,但是需要加上 UNSAFE 开头,表示是不安...
上一小节我们学习了 react 中类组件的优化方式,对于 hooks 为主流的函数式编程,react 也提供了优化方式 memo 方法,本小节我们来了解下它的用...
开源不易,感谢你的支持,❤ star me if you like concent ^_^
hel-micro,模块联邦sdk化,免构建、热更新、工具链无关的微模块方案 ,欢迎关注与了解
本文主题围绕concent的setup和react的五把钩子来展开,既然提到了setup就离不开composition api这个关键词,准确的说setup是由...
ReactsetState的执行是异步还是同步官方文档是这么说的setState()doesnotalwaysimmediatelyupdatethecomponent.Itmaybatchordefertheupdateuntillater.Thismakesreadingthis.staterightaftercallingsetState()apotentialpitfall.Instead,usecom