react—组件生命周期-CSDN博客

一、生命周期概述

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

二、生命周期-挂载时

钩子 函数

触发时机

作用

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中尽量保持精简


原网址: 访问
创建于: 2024-01-29 12:34:23
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论