温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

React组件的常用生命周期函数怎么使用

发布时间:2022-08-15 16:13:33 来源:亿速云 阅读:193 作者:iii 栏目:开发技术

这篇文章主要介绍了React组件的常用生命周期函数怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇React组件的常用生命周期函数怎么使用文章都会有所收获,下面我们一起来看看吧。

1. 概述

  • 意义:组件的生命周期有助于理解组件的运行方式、完成更复杂的组件功能、分析组件错误原因等。

  • 组件的生命周期:组件从被创建到挂载到页面中运行,再到组件不用时卸载的过程。

  • 生命周期的每个阶段总是伴随着一些方法调用,这些方法就是生命周期的钩子函数。

  • 钩子函数的作用:为开发人员在不同阶段操作组件提供了时机。

  • 只有类组件才有生命周期。

2. 生命周期的三个阶段

  • 每个阶段的执行时机

  • 每个阶段钩子函数的执行顺序

  • 每个阶段钩子函数的作用

2.1. 创建时(挂载阶段)

  • 执行时机:组件创建时(页面加载时)

  • 执行顺序:constructor() -> render() -> componentDidMount()

  • 钩子函数的作用:

钩子函数触发时机作用
constructor创建组件时,最先执行1.初始化state 2.为事件处理程序绑定 this
render每次组件渲染都会触发渲染 UI (注意:不能调用setState())
componentDidMount组件挂载(完成 DOM 渲染)后1.发送网络请求 2.DOM 操作
// 导入ract
import React from 'react'
import ReactDOM from 'react-dom'

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

    // 1.初始化state
    this.state = {
      count: 0
    }

    // 2.解决事件处理程序this指向问题
    this.handleClick = this.handleClick.bind(this)

    console.warn('生命周期钩子函数:constructor')
  }
  componentDidMount() {
    // 1.发送ajax请求,获取远程数据
    // axios.get('http://api....')

    // 2.进行DOM操作
    const title = document.getElementById('title')
    console.log(title)

    console.warn('生命周期钩子函数:componentDidMount')
  }

  // 事件处理程序
  handleClick() {
    this.setState({
      count: 1
    })
  }

  render() {
    console.warn('生命周期钩子函数:render')

    // 错误演示(不能调用setState())
    // this.setState({
    //   count: 2
    // })

    return (
      <div>
        <h2 id='title'>统计豆豆被打的次数:{this.state.count}</h2>
        <button id='btn' onClick={this.handleClick}>打豆豆</button>
      </div>
    )
  }
}
ReactDOM.render(<App />, document.getElementById('root'))

2.2. 更新时(更新阶段)

  • 执行时机:setState()、forceUpdate()、组件接收到新的props。

  • 说明:以上任意一种变化,组件就会重新渲染。

  • 执行顺序:render() -> componentDidUpdate()

钩子函数触发时机作用
render每次组件渲染都会触发渲染 UI (与挂载阶段是同一个render)
componentDidUpdate组件更新(完成 DOM 渲染)后1.发送网络请求 2.DOM 操作 注意:如果要 setState() 必须放在一个if条件中
// 导入ract
import React from 'react'
import ReactDOM from 'react-dom'

// 父组件
class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      count: 0
    }
  }

  // 事件处理程序
  handleClick = () => {
    // 执行时机:setState()
    this.setState({
      count: this.state.count + 1
    })

    // 执行时机:强制更新
    // this.forceUpdate()
  }

  render() {
    return (
      <div>
        {/* 执行时机:组件接收到新的props */}
        <ShowCount count={this.state.count} />
        <button onClick={this.handleClick}>打豆豆</button>
      </div>
    )
  }
}

// 子组件
class ShowCount extends React.Component {
  render() {
    console.warn('组件ShowCount的生命周期钩子函数:render')
    return (<h2 id='title'>统计豆豆被打的次数:{this.props.count}</h2>)
  }

  // 注意:如果要调用 setState() 更新状态,必须要放在一个 if 条件中
  // 因为:如果直接调用 setState(),也会导致递归更新!!!
  componentDidUpdate(prevProps) {
    // componentDidUpdate的作用:获取DOM
    const title = document.getElementById('title')
    console.log(title)

    // 正确做法:比较更新前后的props是否相同,来决定是否重新渲染组件
    console.log('上一次的props:', prevProps, ',当前的props:', this.props)
    if (prevProps.count !== this.props.count) {
      this.setState({})

      // componentDidUpdate的作用:发送ajax请求数据
      // axios.get('http://api....')
    }

    // 错误演示
    // this.setState({})

    console.warn('组件ShowCount的生命周期钩子函数:componentDidUpdate')
  }
}
ReactDOM.render(<App />, document.getElementById('root'))

2.3. 卸载时(卸载阶段)

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

钩子函数触发时机作用
componentWillUnmount组件卸载(从页面中消失)执行清理工作(比如:清理定时器等)
// 导入ract
import React from 'react'
import ReactDOM from 'react-dom'

// 父组件
class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      count: 0
    }
  }

  // 事件处理程序
  handleClick = () => {
    this.setState({
      count: this.state.count + 1
    })
  }

  render() {
    return (
      <div>
        {
          this.state.count > 5 ? <p>豆豆被打死了</p> : <ShowCount count={this.state.count} />
        }
        <button onClick={this.handleClick}>打豆豆</button>
      </div>
    )
  }
}

// 子组件
class ShowCount extends React.Component {
  componentDidMount() {
    this.timerId = setInterval(() => {
      console.log('定时器正在执行~')
    }, 500)
  }

  render() {
    return (<h2 id='title'>统计豆豆被打的次数:{this.props.count}</h2>)
  }

  componentWillUnmount() {
    console.warn('组件ShowCount的生命周期钩子函数:componentWillUnmount')

    // 清理定时器
    clearInterval(this.timerId)
  }

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

关于“React组件的常用生命周期函数怎么使用”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“React组件的常用生命周期函数怎么使用”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI