React组件生命周期

componentWillMount 组件将要挂载,可以进行api的数据获取

componentDidMount 组件已经挂载,可以进行dom操作

下面就看一下页面运行后的输出语句,可以看到是先执行componentWillMount 组件,再去执行componentDidMount组件的


此时我们加上构造器和组件渲染的过程(数字是刷新后加上去的执行顺序,方便理解)

 此时再次刷新页面,可以看到构造函数执行后会去执行componentWillMount组件,并对组件进行render中的渲染操作,然后组件就会完成挂载,输出如下


componentWillReceiveProps ⽗组件传递的属性有变化,做相应响应

shouldComponentUpdate 组件是否需要更新,返回布尔值,优化点

componentWillUpdate 组件将要更新

componentDidUpdate 组件已经更新

componentWillUnmount 组件已经销毁

下面直接写出所有的组件,全部输出,增加了两个定时器,第一个定时器显示组件传递的属性被更新,第二个定时器用来控制组件的更新

import React, { Component } from 'react'

class LifecycleChildren extends Component {
    constructor(props){
        super(props)
        console.log('1.构造函数')
    }

    componentWillMount() {
        //组件将要挂载,此时可以进行api调用和获取数据,但是不可以进行dom操作
        console.log('2.组件将要挂载')
    }

    componentDidMount () {
        //组件已经挂载,可以进行dom操作
        console.log('4.组件已经挂载')
    }

    componentWillReceiveProps(){
        //父组件传递的属性有变化,可以在这个函数做相应的相应操作
        console.log('5.父组件传递的属性更新')
    }

    shouldComponentUpdate(){
        //组件是否需要更新,需要返回一个布尔值,返回true更新,false不更新
        console.log('6.组件是否应该更新,需要返回布尔值')
        return true
    }

    componentWillUpdate(){
        //组件将要更新
        console.log('7.组件将要更新')
    }

    componentDidUpdate(){
        //组件已经更新
        console.log('8.组件已经更新')
    }

    componentWillUnmount(){
        //组件销毁
        console.log('组件已经销毁')
    }

    render() {
        console.log('3.组件渲染')
        return (
            <div>
                组件的生命周期
            </div>
        )
    }
}


export default class Lifecycles extends Component {
    constructor(props){
        super(props)
        this.state={
            children:'我是生命周期',
            showChildren:true
        }
        
        setTimeout(()=>{
            this.setState({
                children:'update'
            })
        },2000)

        setTimeout(()=>{
            this.setState({
                showChildren:false
            })
        },4000)
    }
    render() {
        return (
            <div>
                {this.state.showChildren?<LifecycleChildren title={this.state.children}></LifecycleChildren>:<div>组件已销毁</div>}
            </div>
        )
    }
}

运行效果图如下,会先执行1234,2秒后执行属性更新,再2秒后由于组件显示更新为了false,所以组件销毁

 

 本篇文章只是浅层的了解一下组件的生命周期,并没有做深入的探索,只适用于我这种小白入门的一个大概了解,仅供参考。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值