react—组件生命周期

一、生命周期概述

组件的生命周期是指组件从被创建到挂载到页面中运行起来,再到组件不用时卸载的过程,注意,只有类组件才有生命周期,函数组件是没有的。(类组件需要实例化 函数组件不需要实例化)

二、生命周期-挂载时

钩子 函数

触发时机

作用

constructor

创建组件时,最先执行,初始化的时候只执行一次

1. 初始化state  2. 创建 Ref 3. 使用 bind 解决 this 指向问题等

render

每次组件渲染都会触发

渲染UI(注意: 不能在里面调用setState()

componentDidMount

组件挂载(完成DOM渲染)后执行,初始化的时候执行一次

1. 发送网络请求   2.DOM操作

 示例:

这三个的执行顺序为:

                        constructor    ===》  render   ===》  componentDidMount

import React from "react";

class App extends React.Component{
  //目前很少使用 定义数据我们可以直接用state定义
  constructor() { 
    super()
    console.log('constructor')
  }

  // 通常会发送Ajax请求  类似于Vue里的mounted
  componentDidMount() {
    console.log('componentDidMount')
  }
  
  state = {
    count: 0
  }

  clickCount = () => {
    this.setState({
      count: this.state.count + 1
    })
  }

  // 只要视图变化 render就会执行
  render() {
    console.log('render')
    return (
      <div className="App">
        <button onClick={this.clickCount}>{this.state.count}</button>
      </div>
    );
  }
}

export default App;

三、生命周期-更新时

执行顺序为:

                                                render ===》componentDidUpdate 

钩子函数

触发时机

作用

render

每次组件渲染都会触发

渲染UI(与 挂载阶段 是同一个render)

componentDidUpdate

组件更新后(DOM渲染完毕)

DOM操作,可以获取到更新后的DOM内容,不要直接调用setState

四、生命周期-卸载时

钩子函数

触发时机

作用

componentWillUnmount

组件卸载(从页面中消失)

执行清理工作(比如:清理定时器等)

示例 :

清除子组件定时器

import React from "react";

class TestComponent extends React.Component{
  time = null

  componentDidMount() {
    this.time = setInterval(() => {
      console.log('开启定时器')
    },2000)
  }

  componentWillUnmount() {
    console.log('componentWillUnmount-销毁')
    // 清理定时器
    clearInterval(this.time)
  }
  render() {
    return (
      <div>
        子组件
      </div>
    )
  }
}

class App extends React.Component{
  state = {
    count: 0,
    show: true
  }

  clickCount = () => {
    this.setState({
      count: this.state.count + 1,
      show: !this.state.show
    })
  }

  render() {
    console.log('render')
    return (
      <div className="App"}>
        <button onClick={this.clickCount}>{this.state.count}</button>
        {/* 通过一个数据状态的切换 让Test组件进行销毁重建 这时就会发生组件卸载 */}
        {this.state.show ? <TestComponent  /> : null}
      </div>
    );
  }
}

export default App;

注意事项:

1、如果要用到的数据是组件的状态需要去影响视图那就定义到state中去

2、若我们需要的数据不和视图绑定 那么定义成一个普通的实例属性就可以了

3、state中尽量保持精简

  • 22
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值