react 生命周期

1. 生命周期

组件从创建到消亡经历的一系列过程被称为组件的生命周期;

生命周期里的函数也被称作钩子函数;

定义组件的时候重写钩子函数可以做特定的工作

在这里插入图片描述

3.生命周期流程
  • 第一次页面渲染 ReactDOM.render()
    1. constructor(): 创建对象初始化 state
    1. componentWillMount() : 组件即将挂载
    1. render() : 组件挂载
    1. componentDidMount() : 组件已经挂载
  • 更新: this.setState = {}
    1. componentWillUpdate() : 将要更新回调
    1. render() : 更新(重新渲染)
    1. componentDidUpdate() : 已经更新回调
  • 移除组件 ReactDOM.unmountComponentAtNode(containerDom)
    1. componentWillUnmount() : 组件将要被移除回调
4. 重要的钩子函数
  1. render(): 初始化渲染或更新渲染调用
  2. componentDidMount(): 开启监听, 发送 ajax 请求
  3. componentWillUnmount(): 做一些收尾工作, 如: 清理定时器
  4. componentWillReceiveProps(): 接受父组件改变后的props需要重新渲染组件时用

import React, { Component } from 'react';
import { unmountComponentAtNode } from 'react-dom';


class Life extends Component{
  constructor(){
    super(...arguments)

    this.state = {
      opacity: 1
    }
  }

  // 页面渲染完成执行
  componentDidMount() {
    this.timer = setInterval(()=>{
      let {opacity} = this.state;
      opacity -= 0.1
      if(opacity<=0) opacity  = 1;
      this.setState({opacity})
    }, 200)
  }

  // 点击按钮执行
  handClick = ()=>{
    unmountComponentAtNode(document.getElementById('root'))
  }

  // 组件销毁
  componentWillUnmount(){
    clearInterval(this.timer)
  }

  render(){
    const {opacity} = this.state
    return(
      <div>  
        <h2 style={{opacity}}> react 太难了 </h2>  
        <button onClick={this.handClick}> 不活了 </button>
       </div>
    )
  }
}


class App extends Component {
  render() {
    return (
      <div>
          <Life/>
      </div>
    );
  }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值