美文网首页
react基础-生命周期-(2021+2022整理)

react基础-生命周期-(2021+2022整理)

作者: 东邪_黄药师 | 来源:发表于2023-10-09 00:30 被阅读0次

生命周期阶段

image.png

1.创建时(挂载阶段)

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


    执行顺序.png

钩子函数的触发时机.png
import React from 'react'
import ReactDOM from 'react-dom'

/* 
  组件生命周期
*/

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

    // 初始化state
    this.state = {
      count: 0
    }
    // 处理this指向问题

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

  // 1 进行DOM操作
  // 2 发送ajax请求,获取远程数据
  componentDidMount() {
    // axios.get('http://api.....')

    const title = document.getElementById('title')
    console.log(title)
    console.warn('生命周期钩子函数: componentDidMount')
  }

  render() {
    // 错误演示!!! 不要在render中调用setState()
    // this.setState({
    //   count: 1
    // })
    console.warn('生命周期钩子函数: render')

    return (
      <div>
        <h1 id="title">统计豆豆被打的次数:</h1>
        <button id="btn">打豆豆</button>
      </div>
    )
  }
}

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

2.更新时

image.png

执行时机:setState()、 forceUpdate()、 组件接收到新的props
说明:以上三者任意一种变化,组件就会重新渲染

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

/* 
  组件生命周期
*/

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

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

  // 打豆豆
  handleClick = () => {
    // this.setState({
    //   count: this.state.count + 1
    // })
    this.forceUpdate()
  }

  render() {
    console.warn('生命周期钩子函数: render')
    return (
      <div>
        <Counter count={this.state.count} />
        <button onClick={this.handleClick}>打豆豆</button>
      </div>
    )
  }
}

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


}

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

执行顺序:


执行顺序.png
image.png
import React from 'react'
import ReactDOM from 'react-dom'

/* 
  组件生命周期
*/

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

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

  // 打豆豆
  handleClick = () => {
    this.setState({
      count: this.state.count + 1
    })

  }

  render() {
    console.warn('生命周期钩子函数: render')
    return (
      <div>
        <Counter count={this.state.count} />
        <button onClick={this.handleClick}>打豆豆</button>
      </div>
    )
  }
}

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


  // 注意:如果要调用 setState() 更新状态,必须要放在一个 if 条件中
  // 因为:如果直接调用 setState() 更新状态,也会导致递归更新!!!
  componentDidUpdate(prevProps) {
    console.warn('--子组件--生命周期钩子函数: componentDidUpdate')
    //   // 错误演示!!!
    // this.setState({})
    // // 正确的
    // const title = document.getElementById('title')
    // console.log(title.innerHTML)

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

  }
}

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

3.卸载时

image.png

情节操作:点击3次清理定时器

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

/* 
  组件生命周期
*/

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

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

  // 打豆豆
  handleClick = () => {
    this.setState({
      count: this.state.count + 1
    })
  }

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

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

  render() {
    return <h1>统计豆豆被打的次数:{this.props.count}</h1>
  }

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

    // 清理定时器
    clearInterval(this.timerId)
    console.log('定时器已被清理')
  }
}

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

新版完整生命会走棋钩子函数

image.png
getDerivedStateFromProps()
  • getDerivedStateFromProps 会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容
  • 不管原因是什么,都会在每次渲染前触发此方法
shouldComponentUpdate()
  • 根据 shouldComponentUpdate() 的返回值,判断 React 组件的输出是否受当前 state 或 props 更改的影响。默认行为是 state 每次发生变化组件都会重新渲染
  • 当 props 或 state 发生变化时,shouldComponentUpdate() 会在渲染执行之前被调用。返回值默认为 true
getSnapshotBeforeUpdate()
  • getSnapshotBeforeUpdate() 在最近一次渲染输出(提交到 DOM 节点)之前调用。它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)。此生命周期的任何返回值将作为参数传递给 componentDidUpdate()
  • 此用法并不常见,但它可能出现在 UI 处理中,如需要以特殊方式处理滚动位置的聊天线程等

2022重新学习整理出来的

React的生命周期函数.png

相关文章

  • React面试题 整理脑图

    react基础 React生命周期 react-router react进阶 react Hooks redux 其他

  • 生命周期

    React基础知识 一 、生命周期 二、组件间的传参 componentWillReceiveProps生命周期在...

  • React 文档 Part 1

    —— 基础知识、JSX介绍、React 元素、组件和属性、状态和生命周期 此文档来自 React 官方文档,在英文...

  • 简述React生命周期

    React 适合0基础教程快速上手 github地址 React组件的生命周期(必须掌握) 创建期(五个阶段...

  • 2020-11-10 今日自我总结(日后进行完善和进一步总结)

    自我分析: react中的知识掌握不牢固,对react生命周期掌握比较浅显 js的基础知识比较弱,导致对react...

  • React概念图

    React概念图 React组件生命周期概念图 参考文档:React入门教程 组件生命周期React:组件生命周期...

  • React基础篇之组件的生命周期

    引出生命周期 react生命周期(旧) react生命周期(新) getSnapshotBeforeUpdate的...

  • React 基础整理

    1. React 介绍 React 是一个用于构建用户界面的 JavaScript 库,它只负责应用的视图层,帮助...

  • React生命周期

    React v16.0前的生命周期 React v16.4+ 的生命周期图 React v16.9后这些生命周期钩...

  • React v16 生命周期

    React 16 生命周期 React 16.3 新增的生命周期方法 逐渐废弃的生命周期方法: 一般将生命周期分成...

网友评论

      本文标题:react基础-生命周期-(2021+2022整理)

      本文链接:https://www.haomeiwen.com/subject/scuhwrtx.html