React挂载时使用到的生命周期

1.constructor()

在这个周期中可以做的事情:
 1. 初始化状态
 2. 绑定this
 3.  创建ref

2.getDerivedStateFromProps(props,state)

在这个周期中可以做的事情:
当父组件更新的时候,会传一些的新的属性进来,当有的属性我有用到的时候,这里返回的对象就会去跟状态 this.state={}里的对应属性合并

3.render()

注意:render()中不能使用setState()方法,不然会引起无限更新
this.setState({
show:false
})

4.componentDidMount()

在componentDidMount()周期可以做的事情:
1.注册事件;
2.发送请求
3.订阅 redux subscribe 订阅数据的方法


import React, { Component } from 'react';
// 挂载时
class App extends Component {
    // state={}
    constructor(props){
        super(props)
        console.log("1.执行了constructor")
    //   constructor()周期可以做的事情
    //1.初始化状态
    this.state={}
    // 2.绑定this
   this.handleClick=this.handleClick.bind(this)
   //3.创建ref
   this.ref=React.createRef()
    }
    handleClick(){}
  static getDerivedStateFromProps(props,state){
        console.log('2.执行力getDerivedStatefromprops')
        // 作用:当父组件更新的时候,会传一些的新的属性进来,当有的属性我有用到的时候,这里返回的对象就会去跟状态  this.state={}里的对应属性合并
        return {
            show:true
        }
    }
    render() {
        console.log('3.执行了render()')
        //注意:render()中不能使用setState()方法,不然会引起无限更新
        // this.setState({
        //     show:false
        // })
        return (
            <div>
                <button id="btn">按钮被点击了</button>
            </div>
        );
    }
    componentDidMount(){
        console.log("4.执行力componentDidMount")
        // 在componentDidMount()周期可以做的事情
        // 1.注册事件,定时器
        document.getElementById('btn').addEventListener('click',function(){
            console.log("按钮被点击了")
        })
        // 2.发送请求
      
        // 3.订阅 redux subscribe 订阅数据的方法

    }
}

export default App;

在这里插入图片描述

生命周期全过程

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值