react 组件生命周期 ===

目录

生命周期

钩子函数

react类组件的生命周期钩子函数-整体说明

组件生命周期-挂载阶段

组件生命周期-更新阶段

更新阶段的钩子

三种触发更新

更新阶段能做的事情

组件生命周期-卸载阶段


生命周期

生命周期:一个事物从创建到最后消亡经历的整个过程

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

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

钩子函数

在生命周期的不同阶段,会自动被调用执行的函数,为开发人员在不同阶段操作组件提供了时机。

注意:只有类组件 才有生命周期

react类组件的生命周期钩子函数-整体说明

组件生命周期-挂载阶段

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

执行顺序:

组件生命周期-更新阶段

更新阶段的钩子

三种触发更新

  1. 调用setState。它能改数据&& 更新页面

  2. 调用forceUpdate()

  3. 组件接收到新的props

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

更新阶段能做的事情

 如果有些事情是需要每次更新去做的,就可以写在componentDidUpdate中。例如:数据本地存储

组件生命周期-卸载阶段

执行时机:组件销毁

示例:清理定时器&&移除事件

/* eslint-disable react/prop-types */
import React, { Component, createRef } from 'react'
import ReactDOM from 'react-dom'

class Son extends Component {
  constructor () {
    super()

    this.timer = setInterval(() => {
      console.log('子组件:', Date.now())
    }, 1000)
    this.fn = () => {
      console.log('鼠标移动...')
    }
    window.addEventListener('mousemove', this.fn)
  }

  render () {
    return <div>子组件:{this.props.content}</div>
  }

  componentDidUpdate () {
    console.log('子组件: componentDidUpdate')
  }

  componentWillUnmount () {
    console.log('子组件 卸载: componentWillUnmount')
    // 删除事件
    window.removeEventListener('mousemove', this.fn)
    // 删除定时器
    clearInterval(this.timer)
  }
}

export default class App extends Component {
  constructor () {
    super()
    console.log('1. constructor')
    this.state = {
      content: '',
      isShow: true
    }
    this.refTxt = createRef()
  }

  hChange = (e) => {
    this.setState({ content: e.target.value })
  }

  click = () => {
    this.forceUpdate()
  }

  render () {
    console.log('2. render')
    return (
      <div>
        <button onClick={this.click}>更新</button>
        组件<input value={this.state.content} onChange={this.hChange} />
        <br />
        {this.state.isShow && <Son content={this.state.content} />}
      </div>
    )
  }

  componentDidMount () {
    console.log('3. componentDidMount')
    console.log(this.refTxt.current)

    // axios.get()
  }

  componentDidUpdate () {
    console.log('更新完成: componentDidUpdate')
  }
}

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

猜你喜欢

转载自blog.csdn.net/weixin_58726419/article/details/121234376