React 之组件的生命周期

一、生命周期概述

  • 生命周期: 组件从创建到加载运行再到不用卸载的整个过程就是生命周期 (创建 --> 加载运行 --> 卸载)
  • 掌握组件生命周期有助于我们理解组件的运行方式,完成更复杂的功能,分析组件错位u原因以及解决错误
  • 生命周期的每个阶段中都有一些方法调用,这些方法就是生命周期的钩子函数,钩子函数能够实现更多的功能
  • 只有类组件才有生命周期

二、生命周期的三个阶段

1、创建阶段

执行时机:只要页面一经加载,组件一旦被渲染,下面的三个钩子函数就会执行

顺序执行: constructor —> render —> componentDidMount

import React from 'react'
import ReactDOM from 'react-dom'

class Hello extends React.Component {
  constructor (props) {
    super(props)

    console.log('执行了constructor 函数')
  }

  render () {
    console.log('执行了 render 函数')
    return (
      <div id="title">Hello 组件</div>
    )
  }
  componentDidMount () {
    console.log('执行了 componentDidMount 函数')
    const title = document.querySelector('#title')
    console.log(title)
  }
}
ReactDOM.render(<Hello />, document.getElementById('root'))

在这里插入图片描述

钩子函数触发时机作用
constructor创建组件时1、初始化 state;2、使用 bind 修改方法的this指向
render每次渲染组件时渲染页面 (不能调用 setState 方法)
componentDidMount渲染完成后1、发送网络请求;2、DOM操作

2、更新阶段

更新时会顺序执行两个函数: render —> componentDidUpdate

有三种情况会更新组件:

  • new props:组件接收到新属性的时候render 会重新渲染, props 的值会发生改变
  • forceUpdate(): 调用 forceUpdate() 强制进行更新
  • setState(): 调用了setState 方法更新数据
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
  constructor () {
    super()

    this.state = {
      count:0
    }

    //console.log('执行了constructor 函数')
  }
  handleClick = () => {
    // 调用 forceUpdate 方法能够强制更新
  //  this.forceUpdate()
    // 调用 setState 方法更新数据后触发更新
    this.setState({
      count:this.state.count + 1
    })
  }

  render () {
    console.log('执行了 render 函数')
    return (
      <div>
        <Counter count={this.state.count}/>
        <button onClick={this.handleClick}>打满满</button>
      </div>
    )
  }

  componentDidMount () {
    console.log('执行了 componentDidMount 函数')
  }
  componentDidUpdate () {
    console.log('执行了 componentDidUpdate 函数')
  }
  
}
class Counter extends React.Component{
  render(){
    return <h1>统计打满满的次数:{this.props.count}</h1>
  }
}
ReactDOM.render(<App />, document.getElementById('root'))
钩子函数触发时机作用
render每次渲染渲染页面
componentDidUpdate更新组件完成发送网络请求;DOM操作;注意: 如果要执行 setState(), 必须有结束条件
  componentDidUpdate (preProps) {
    console.log('执行了 componentDidUpdate 函数')
   //比较更新前后的props 是否相同,来决定是否重新渲染组件
   // console.log('上一次的props:',preProps,'当前的props:',this.props)
    if(preProps.count !== this.props.count){
      this.setState({})
    }
  }
 

如果要调用setState() 更新状态,必须放在一个if 条件中,因为如果直接调用setState() 更新状态,会导致递归更新陷入死递归!!!

  • setState 会调用 render 和 componentDidUpdate
  • componentDidUpdate 又会再次调用 setState

3、卸载阶段

执行时机:组件从页面中消失

钩子函数触发时机作用
componentWillUnmount卸载组件执行清理工作
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
  constructor () {
    super()

    this.state = {
      count:0
    }

    //console.log('执行了constructor 函数')
  }
  handleClick = () => {
    // 调用 forceUpdate 方法能够强制更新
  //  this.forceUpdate()
    // 调用 setState 方法更新数据后触发更新
    this.setState({
      count:this.state.count + 1
    })
  }

  render () {
    console.log('执行了 render 函数')
    return (
      <div>
        {
          this.state.count > 3?
          <p>满满被揍惨了</p>
          :<Counter count={this.state.count}/>
        }
        
        <button onClick={this.handleClick}>打满满</button>
      </div>
    )
  }


  componentDidUpdate (preProps) {
    console.log('执行了 componentDidUpdate 函数')
   //比较更新前后的props 是否相同,来决定是否重新渲染组件
    console.log('上一次的props:',preProps,'当前的props:',this.props)
    if(preProps.count !== this.props.count){
      this.setState({})
    }
  }

}
class Counter extends React.Component{
  componentDidMount(){
    //开启定时器
    setInterval(()=>{
      console.log('定时器正在执行');
    },500)
  }
  render(){
    return <h1 id='title'>统计打满满的次数:{this.props.count}</h1>
  }

  componentWillUnmount(){
    console.log('执行了 componentWillUnmount 函数');
    //清理定时器
    clearInterval(this.timerId)
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

在这里插入图片描述
生命周期完整图示:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]:当渲染过程,生命周期或子组件的构造函数中抛出错误时,会调用如下方法: static getDerivedStateFromProps()componentDidCatch() 常用生命周期 1.render() 。 引用\[2\]:当组件实例被创建并插入DOM时,其生命周期调用顺序如下: constructor()static getDerivedStateFromProps()render()componentDidMount() 组件更新时 。 引用\[3\]:组件渲染之后调用,只调用一次 2.4、生命周期函数代码示例 import React, { Component } from 'react' export default class OldReactComponent extends Component { constructor(props) { super(props) // getDefaultProps:接收初始props // getInitialState:初始化state } state = { } componentWillMount() { // 组件挂载前触发 } render() { return ( <h2>Old React.Component</h2> ) } componentDidMount() { // 组件挂载后触发 } componentWillReceivePorps(nextProps) { // 接收到新的props时触发 } shouldComponentUpdate(nextProps, nextState) { // 组件Props或者state改变时触发,true:更新,false:不更新 return true } componentWillUpdate(nextProps, nextState) { // 组件更新前触发 } componentDidUpdate() { // 组件更新后触发 } componentWillUnmount() { // 组件卸载时触发 } } 3、新的生命周期 3.1、Mounting(加载阶段:涉及4个钩子函数) 。 问题:react函数组件 生命周期 回答: React函数组件生命周期相对简单,只有两个阶段:Mounting(加载阶段)和Unmounting(卸载阶段)。在Mounting阶段,函数组件会依次执行以下生命周期函数:constructor()、render()和componentDidMount()。constructor()函数用于初始化组件的状态和绑定事件处理函数。render()函数用于渲染组件的UI。componentDidMount()函数组件被插入DOM后调用,可以进行一些异步操作或订阅事件。在Unmounting阶段,函数组件会执行componentWillUnmount()函数,在组件被卸载前进行一些清理工作,比如取消订阅事件或清除定时器。除了这些生命周期函数函数组件没有其他生命周期函数可用。 #### 引用[.reference_title] - *1* *2* [React生命周期详解](https://blog.csdn.net/weixin_46872121/article/details/126623679)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [关于React组件生命周期函数的详解](https://blog.csdn.net/p445098355/article/details/104667187)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值