react 生命周期 钩子函数(笔记 1)

一. constructor(){}  : 初始化 

         this 问题

      class App extends React.Component{
        state ={}

        constructor(props){
          super(props) //this.prosp=props
          console.log(this);
          //状态初始化
          this.state={age:0}
          //this 绑定
          this.go=this.go.bind(this)
        }

        go(){
          console.log(this);
        }

        render(){
          return(
            <div> App </div>
          )
        }
      }

1. constructor 中的 super( props ) 是用来给 props 实例化的 含义为 this.props=props

2. 状态初始化

this.state = { age:0 }

3. this 绑定

this.go = this.go.bind ( this ) 

二. componentWillMount(){}  :第一次组件渲染之前(render执行之前)只会执行一次

      class App extends React.Component{
        
        constructor(props){
          console.log("----constructor");
           super(props) //this.prosp=props
        }

        //componentWillMount(){
        //  console.log("----componentWillMount");
        //}

        UNSAFE_componentWillMount(){
          console.log("----UNSAFE_componentWillMount");
        }

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

执行顺序如下:

componentWillMount 会在 render 之前执行 并且 componentWillMount  中已能获取当前组件的实例 ( state 、props ) 

不可以通过 this 的方式修改数据,但可以通过 setState( ) 的方法修改数据 并且 setState( ) 重新渲染不会触发 render () 

由于 componentWillMount(){} 使用时因异步请求问题不确定执行在哪一阶段 ( 之前、之后、之中 )  所以后改版为 UNSAFE_componentWillMount(){}

三. render(){}   渲染   :第一次 挂载 和 更新

解析 jsx 构建虚拟 DOM => ( diff算法 ) => 真实DOM => 页面视图

class 组件必须实现的方法

render 是一个纯函数

注意:render 中 不要使用 this.setState() 重新渲染数据 会造成死循环( 导致内存溢出 )

四. componentDidMount(){}   :在第一次渲染之后立即执行

进行一些依赖于 DOM 的相关操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值