美文网首页React
React 组件的生命周期

React 组件的生命周期

作者: 柏丘君 | 来源:发表于2017-05-31 17:39 被阅读92次

React 组件的一生,是光荣的一生,是革命的一生,在它的一生中会经历这样几个阶段:

  • 装载阶段
  • 更新阶段
  • 销毁阶段

每一阶段都会触发相应的生命周期函数,下面依次来说一说这些生命周期函数。

装载阶段

装载阶段就是组件第一次被渲染时的阶段,这一阶段相关的生命周期函数有:

  • constructor
  • componentWillMount
  • render
  • componentDidMount

下面是这些方法的一些说明:
constructor:用来初始化组件,获取组件的初始属性(props)或状态(state),其作用类似于 ES5 createClass 写法中的 getInitialState 和 getDefaultProps 函数。
componentWillMount:在组件即将装载前调用。
render:用来生成一个 JSX 描述结构,告诉 React 本次要装载哪些东西,需要注意的是,render方法只用来返回一个 JSX 结构,并不负责装载,具体的装载工作由 React 完成
componentDidMount:在组件被装载之后调用,此时已经完成了 DOM 更新,组件已经被装载到真实的 DOM 树中了,可以进行相应的 DOM 操作,比如添加原生的 DOM 事件就应该放在 componentDidMount 中进行。
看一个例子:

import React,{ Component } from "react";
import "./App.css";

export default class App extends Component{
    constructor(props){
        super(props);
        console.log("constructor")
    }

    componentWillMount() {
        console.log("componentWillMount")
    }

    componentDidMount(){
        console.log("componentDidMount")
    }

    render(){
        console.log("render")
        return(
            <div className = "App-div">
                
            </div>
        );
    }
}

打开浏览器,控制台中输出的结果为:

constructor
componentWillMount
render
componentDidMount

多个组件的情况

如果 App 组件中渲染了其他的组件,那么这些组件的生命周期函数是怎样调用的呢?
新建一个 SubComponent.js:

import React,{ Component } from "react";

export default class Sub extends Component{
    constructor(props){
        super(props);
        console.log("constructor")
    }

    componentWillMount() {
        console.log("componentWillMount")
    }

    componentDidMount(){
        console.log("componentDidMount")
    }

    render(){
        console.log("render")
        return(
            <div>我是子组件</div>
        );
    }
}

修改 App.js,让其渲染两个子组件:

import React,{ Component } from "react";
import Sub from "./SubComponent.js";
import "./App.css";

export default class App extends Component{
    
    render(){
        const SubArr = [1,2].map((v)=>{
            return <Sub key = {v} />
        });

        return(
            <div className = "App-div">
                { SubArr }
            </div>
        );
    }
}

打开浏览器,看下控制台中的输出:

constructor
componentWillMount
render
constructor
componentWillMount
render
componentDidMount
componentDidMount

这两个子组件的 componentDidMount 函数并不是在 render 函数之后执行,而是放在最后执行了,为什么呢?
还是回到上面那句话:render 函数只用来生成 JSX 组件结构,不负责装载工作,具体的状态工作交个 React 完成
React 需要在形成完整的 JSX 结构之后才进行装载,也就是说,要在两个 render 函数都调用完成后才进行装载工作,而后再调用 componentDidMount 生命周期函数。

更新阶段

如果组件中的 state 或者 props 发生了改变,React 就会更新该组件,此时会调用更新阶段中相关的生命周期函数:

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate

componentWillReceiveProps 函数在传递给子组件的 props 变化或者父组件更新时调用。
修改 SubComponent.js:

import React,{ Component } from "react";

export default class Sub extends Component{
    componentWillReceiveProps(nextProps) {
        console.log("componentWillReceiveProps");
    }

    shouldComponentUpdate(nextProps, nextState) {
        console.log("shouldComponentUpdate");
        return true;
    }

    componentDidUpdate(prevProps, prevState) {
        console.log("componentDidUpdate");
    }

    render(){
        console.log("render")
        return(
            <div>我是子组件</div>
        );
    }
}

修改 App.js,增加一个按钮,点击时强制更新:

import React,{ Component } from "react";
import Sub from "./SubComponent.js";
import "./App.css";

export default class App extends Component{

    render(){
        const SubArr = [1,2].map((v)=>{
            return <Sub key = {v} />
        });

        return(
            <div className = "App-div">
                <button onClick = { ()=>this.forceUpdate() }>点击强制更新</button>
                { SubArr }
            </div>
        );
    }
}

点击更新按钮,看下控制台的输出:

componentWillReceiveProps
shouldComponentUpdate
render
componentWillReceiveProps
shouldComponentUpdate
render
componentDidUpdate
componentDidUpdate

可见,父组件的更新也会引起子组件的更新,如果父组件中有很多子组件,默认情况下,在父组件进行更新(通常是父组件的 props 或 state 发生变化)或者父组件传递给子组件的 props 发生变化时,会引起所有子组件的更新。如果子组件数量众多,功能复杂,那么进行更新会产生大量的性能浪费,即使是在使用 Virtual DOM 的情况下。针对这种情况,我们就需要使用下面介绍的 shouldComponentUpdate 函数了。
P.S.在使用 setState 时并不会调用 componentWillReceiveProps,而是直接调用 shouldComponentUpdate 函数

shouldComponentUpdate 函数接受两个参数:nextProps 和 nextState,分别表示引发本次组件更新的 props 或 state,该函数的返回值的真假决定组件是否更新,默认返回 true。实际应用场景中,我们可以将这两个参数和组件当前的 props(this.props)和当前的 state(this.state)进行比对,以决定是否更新组件,提高性能。
为了方便演示,给每个子组件传递一个名为 flag 的 prop:

import React,{ Component } from "react";
import Sub from "./SubComponent.js";
import "./App.css";

export default class App extends Component{

    render(){
        const SubArr = [1,2].map((v)=>{
            return <Sub key = {v} flag = "1" />
        });

        return(
            <div className = "App-div">
                <button onClick = { ()=>this.forceUpdate() }>点击强制更新</button>
                { SubArr }
            </div>
        );
    }
}

修改 SubComponent.js:

import React,{ Component } from "react";

export default class Sub extends Component{
    componentWillReceiveProps(nextProps) {
        console.log("componentWillReceiveProps");
    }

    shouldComponentUpdate(nextProps, nextState) {
        return (nextProps.flag !== this.props.flag);
    }

    componentDidUpdate(prevProps, prevState) {
        console.log("componentDidUpdate");
    }

    render(){
        console.log("render")
        return(
            <div>我是子组件</div>
        );
    }
}

控制台的输出结果为:

componentWillReceiveProps
componentWillReceiveProps

父组件更新后,会引起子组件的更新,首先就是调用 componentWillReceiveProps 方法,之后在 shouldComponentUpdate 中进行属性值的判断,由于两次渲染都传递了相同的属性值,因此没有必要更新组件,shouldComponentUpdate 函数返回 false,后面的一系列生命周期函数就不执行了,提高了渲染性能。
componentWillUpdate 函数在组件即将更新时调用。
render 函数用来产出本次更新的 JSX 组件树结构。
componentDidUpdate 函数在组件完成更新后调用。当组件被更新时,会重新绘制 DOM 树。同 componentDidMount 函数,该函数并不是在每个子组件 render 方法执行后立即被执行的,而是等待 DOM 树更新后再执行。

卸载过程

卸载过程就一个函数:

  • componentWillUnmount

该函数用来做一些清理工作,比如如果在组件中使用了原生的 DOM 事件,需要在组件被销毁前移除该事件,防止内存泄露,或者清理定时器等。

完。

相关文章

  • React概念图

    React概念图 React组件生命周期概念图 参考文档:React入门教程 组件生命周期React:组件生命周期...

  • React 组件生命周期

    组件生命周期 参考阅读: component-lifecycle react组件生命周期过程说明 react 组件...

  • React总结

    [toc] 1.React组件生命周期 1.1 生命周期图 组件的生命周期的图如下: 具体可参考React 组件生...

  • 学习并实现react (4)

    实现生命周期 生命周期介绍 React 生命周期图 React 子组件在父组件下的生命周期流程 实现 compon...

  • react(最近搞了一套react项目的视频 全套 有需

    React 组件生命周期在本章节中我们将讨论 React 组件的生命周期。 组件的生命周期可分成三个状态: Mou...

  • Notes On React - Two

    React 的生命周期   React组件 的生命周期大致可分成四个状态:  - Mounting:装配-组件实例...

  • 006@React组件的生命周期.md

    006@React组件的生命周期.md React Native 是基于组件化开发。弄清楚组件的生命周期对于我们开...

  • React 生命周期

    React 生命周期 初始化周期 组件重新渲染生命周期 组件卸载生命周期

  • react组件的生命周期

    第三单元(react组件的生命周期) 课程目标 灵活掌握react组件的生命周期以及组件的活动过程。 能够灵活使用...

  • 四:React 进阶三 (生命周期)

    react(一):组件的生命周期 生命周期函数 在组件运行的某个时刻,会被自动执行的一些函数。 React生命周期...

网友评论

    本文标题:React 组件的生命周期

    本文链接:https://www.haomeiwen.com/subject/gvhjfxtx.html