【React】React组件生命周期以及触发顺序(部分与vue做比较)

最近在学习React,发现其中的生命周期跟Vue有一些共同点,但也有比较明显的区别,并且执行顺序也值得讨论一下,于是总结了一些资料在这里,作为学习记录。

v17.0.1后生命周期图片

在这里插入图片描述

初始化阶段

由ReactDOM.render()触发 —— 初次渲染

  1. constructor() —— 类组件中的构造函数
  2. static getDerivedStateFromProps(props, state) 从props得到一个派生的状态【新增】
  3. render() —— 挂载组件
  4. componentDidMount() —— 组件挂载完成 比较常用
    总结:
    constructor 对标 Vue中的beforeCreate/created
    componentDidMount 对标 Vue中的 Mounted
    在一个完整的生命周期中,constructor 与 componentDidMount 只会执行一次。
    在一个完整的生命周期中,render会执行多次
    注意:
    在React中,我们在componentDidMount 中发请求,绝对不在constructor 中发请求。

更新阶段

由组件内部this.setSate()或父组件重新render触发或强制更新forceUpdate()

  1. getDerivedStateFromProps() —— 从props得到一个派生的状态 【新增】
  2. shouldComponentUpdate() —— 组件是否应该被更新(默认返回true)
  3. render() —— 挂载组件
  4. getSnapshotBeforeUpdate() —— 在更新之前获取快照【新增】
  5. componentDidUpdate(prevProps, prevState, snapshotValue) —— 组件完成更新。
    总结:
    触发组件更新的方式(常用),两种:
    1. 💥props 值的改变
    2. 💥setState() 改变state
      更新阶段触发的钩子函数,有两个
      1. render
      2. componentDidUpdate
        render与componentsDidUpdate 都可以拿到更新后的值。
        render与componentsDidUpdate 中都不能调用setState ,会造成死循环。
        注意:
        不论DOM中有没有使用数据,钩子函数都会被触发。(与vue不同)
        react中的更新,指的是数据更新,而非视图更新。(与vue不同)

卸载组件

由ReactDOM.unmountComponentAtNode()触发

  1. componentWillUnmount() —— 组件即将卸载

重要的勾子

  1. render:初始化渲染或更新渲染调用
  2. componentDidMount:开启监听, 发送ajax请求
  3. componentWillUnmount:做一些收尾工作, 如: 清理定时器

即将废弃的勾子

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate
    现在使用会出现警告,下一个大版本需要加上UNSAFE_前缀才能使用,以后可能会被彻底废弃,不建议使用。

代码案例

效果
在这里插入图片描述
代码展示

父组件:Parent.js

import React, { Component } from 'react';
import { Button } from 'antd';
import Child from './child';const parentStyle = {padding: 40,margin: 20,backgroundColor: 'LightCyan',
};const NAME = 'Parent 组件:';export default class Parent extends Component {constructor() {super();console.log(NAME, 'constructor');this.state = {count: 0,mountChild: true,};}static getDerivedStateFromProps(nextProps, prevState) {console.log(NAME, 'getDerivedStateFromProps');return null;}componentDidMount() {console.log(NAME, 'componentDidMount');}shouldComponentUpdate(nextProps, nextState) {console.log(NAME, 'shouldComponentUpdate');return true;}getSnapshotBeforeUpdate(prevProps, prevState) {console.log(NAME, 'getSnapshotBeforeUpdate');return null;}componentDidUpdate(prevProps, prevState, snapshot) {console.log(NAME, 'componentDidUpdate');}componentWillUnmount() {console.log(NAME, 'componentWillUnmount');}/*** 修改传给子组件属性 count 的方法*/changeNum = () => {let { count } = this.state;this.setState({count: ++count,});};/*** 切换子组件挂载和卸载的方法*/toggleMountChild = () => {const { mountChild } = this.state;this.setState({mountChild: !mountChild,});};render() {console.log(NAME, 'render');const { count, mountChild } = this.state;return (<div style={parentStyle}><div><h3>父组件</h3><Button onClick={this.changeNum}>改变传给子组件的属性 count</Button><br /><br /><Button onClick={this.toggleMountChild}>卸载 / 挂载子组件</Button></div>{mountChild ? <Child count={count} /> : null}</div>);}
}

子组件: Child.js

import React, { Component } from 'react';
import { Button } from 'antd';const childStyle = {padding: 20,margin: 20,backgroundColor: 'LightSkyBlue',
};const NAME = 'Child 组件:';export default class Child extends Component {constructor() {super();console.log(NAME, 'constructor');this.state = {counter: 0,};}static getDerivedStateFromProps(nextProps, prevState) {console.log(NAME, 'getDerivedStateFromProps');return null;}componentDidMount() {console.log(NAME, 'componentDidMount');}shouldComponentUpdate(nextProps, nextState) {console.log(NAME, 'shouldComponentUpdate');return true;}getSnapshotBeforeUpdate(prevProps, prevState) {console.log(NAME, 'getSnapshotBeforeUpdate');return null;}componentDidUpdate(prevProps, prevState, snapshot) {console.log(NAME, 'componentDidUpdate');}componentWillUnmount() {console.log(NAME, 'componentWillUnmount');}changeCounter = () => {let { counter } = this.state;this.setState({counter: ++counter,});};render() {console.log(NAME, 'render');const { count } = this.props;const { counter } = this.state;return (<div style={childStyle}><h3>子组件</h3><p>父组件传过来的属性 count : {count}</p><p>子组件自身状态 counter : {counter}</p><Button onClick={this.changeCounter}>改变自身状态 counter</Button></div>);}
}

从五种组件状态改变的时机来探究生命周期的执行顺序

一、父子组件初始化

父子组件第一次进行渲染加载时:
控制台的打印顺序为:

  • Parent 组件: constructor()
  • Parent 组件: getDerivedStateFromProps()
  • Parent 组件: render()
  • Child 组件: constructor()
  • Child 组件: getDerivedStateFromProps()
  • Child 组件: render()
  • Child 组件: componentDidMount()
  • Parent 组件: componentDidMount()

二、子组件修改自身状态 state

点击子组件 [改变自身状态counter] 按钮,其 [自身状态counter] 值会 +1, 此时控制台的打印顺序为:

  • Child 组件: getDerivedStateFromProps()
  • Child 组件: shouldComponentUpdate()
  • Child 组件: render()
  • Child 组件: getSnapshotBeforeUpdate()
  • Child 组件: componentDidUpdate()

三、修改父组件中传入子组件的 props

点击父组件中的 [改变传给子组件的属性 count] 按钮,则界面上 [父组件传过来的属性 count] 的值会 + 1,控制台的打印顺序为:

  • Parent 组件: getDerivedStateFromProps()
  • Parent 组件: shouldComponentUpdate()
  • Parent 组件: render()
  • Child 组件: getDerivedStateFromProps()
  • Child 组件: shouldComponentUpdate()
  • Child 组件: render()
  • Child 组件: getSnapshotBeforeUpdate()
  • Parent 组件: getSnapshotBeforeUpdate()
  • Child 组件: componentDidUpdate()
  • Parent 组件: componentDidUpdate()

四、卸载子组件

点击父组件中的 [卸载 / 挂载子组件] 按钮,则界面上子组件会消失,控制台的打印顺序为:

  • Parent 组件: getDerivedStateFromProps()
  • Parent 组件: shouldComponentUpdate()
  • Parent 组件: render()
  • Parent 组件: getSnapshotBeforeUpdate()
  • Child 组件: componentWillUnmount()
  • Parent 组件: componentDidUpdate()

五、重新挂载子组件

再次点击父组件中的 [卸载 / 挂载子组件] 按钮,则界面上子组件会重新渲染出来,控制台的打印顺序为:

  • Parent 组件: getDerivedStateFromProps()
  • Parent 组件: shouldComponentUpdate()
  • Parent 组件: render()
  • Child 组件: constructor()
  • Child 组件: getDerivedStateFromProps()
  • Child 组件: render()
  • Parent 组件: getSnapshotBeforeUpdate()
  • Child 组件: componentDidMount()
  • Parent 组件: componentDidUpdate()

父子组件生命周期执行顺序总结:

  • 当子组件自身状态改变时,不会对父组件产生副作用的情况下,父组件不会进行更新,即不会触发父组件的生命周期
  • 当父组件中状态发生变化(包括子组件的挂载以及卸载)时,会触发自身对应的生命周期以及子组件的更新
    • render 以及 render 之前的生命周期,则 父组件先执行
    • render之后的生命周期,子组件先执行,并且与父组件交替执行
  • 当子组件进行卸载时,只会执行自身的 componentWillUnmount 生命周期,不会再触发别的生命周期

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/146436.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

【Java 进阶篇】JDBC插入数据详解

在Java应用程序中&#xff0c;与数据库交互是一项常见的任务。其中&#xff0c;插入数据操作是一种基本的数据库操作之一。本文将详细介绍如何使用Java JDBC&#xff08;Java Database Connectivity&#xff09;来执行插入数据操作。无论您是初学者还是有一定经验的开发人员&am…

CSS详细基础(六)边框样式

本期是CSS基础的最后一篇~ 目录 一.border属性 二.边框属性复合写法 三.CSS修改表格标签 四.内边距属性 五.外边距属性 六.其他杂例 1.盒子元素水平居中 2.清除网页内外元素边距 3.外边距的合并与塌陷 4.padding不会撑大盒子的情况 七.综合案例——新浪导航栏仿真 …

Android studio升级Giraffe | 2022.3.1 Patch 1踩坑

这里写自定义目录标题 not "opens java.io" to unnamed module错误报错信息解决 superclass access check failed: class butterknife.compiler.ButterKnifeProcessor$RScanner报错报错信息解决 Android studio升级Giraffe | 2022.3.1 Patch 1后&#xff0c;出现项目…

imgui开发笔记<1>、ubuntu环境下快速应用

去这个链接下载imgui源码&#xff08;在此之前需要安装opengl glfw3等等&#xff09;&#xff1a; sudo apt-get install libglfw3-dev https://github.com/ocornut/imgui 我这里源码下载到/home/temp/imgui目录下&#xff0c;咱们不需要编译源码成库&#xff0c;而是直接将下…

【Axure高保真原型】3D圆柱图_中继器版

今天和大家分享3D圆柱图_中继器版的原型模板&#xff0c;图表在中继器表格里填写具体的数据&#xff0c;调整坐标系后&#xff0c;就可以根据表格数据自动生成对应高度的圆柱图&#xff0c;鼠标移入时&#xff0c;可以查看对应圆柱体的数据……具体效果可以打开下方原型地址体验…

网络安全渗透测试工具之skipfish

网络安全渗透测试工具skipfish介绍 在数字化的时代,Web 应用程序安全成为了首要任务。想象一下,您是一位勇敢的安全冒险家,迎接着那些隐藏在 Web 应用程序中的未知风险。而在这个冒险之旅中,您需要一款强大的工具来帮助您发现漏洞,揭示弱点。而这个工具就是 Skipfish。 …

LeetCode 周赛上分之旅 #48 一道简单的树上动态规划问题

⭐️ 本文已收录到 AndroidFamily&#xff0c;技术和职场问题&#xff0c;请关注公众号 [彭旭锐] 和 BaguTree Pro 知识星球提问。 学习数据结构与算法的关键在于掌握问题背后的算法思维框架&#xff0c;你的思考越抽象&#xff0c;它能覆盖的问题域就越广&#xff0c;理解难度…

点击、拖拉拽,BI系统让业务掌握数据分析主动权

在今天的商业环境中&#xff0c;数据分析已经成为企业获取竞争优势的关键因素之一。然而&#xff0c;许多企业在面对复杂的数据分析工具时&#xff0c;却常常感到困扰。这些工具往往需要专业的技术人员操作&#xff0c;而且界面复杂&#xff0c;难以理解和使用。对业务人员来说…

阿里云 Oss 权限控制

前言 最近公司的私有 Oss 服务满了&#xff0c;且 Oss 地址需要设置权限&#xff0c;只有当前系统的登录用户才能访问 Oss 下载地址。一开始想着用 Nginx 做个转发来着&#xff0c;Nginx 每当检测当前请求包含特定的 Oss 地址就转发到我们的统一鉴权接口上去&#xff0c;但是紧…

picoctf_2018_shellcode

picoctf_2018_shellcode Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments32位&#xff0c;啥都没开 这个看着挺大的&#xff0c;直接来个ROPchain&#xff0c;…

Redis缓存穿透、击穿和雪崩

面试高频 服务的高可用问题&#xff01; 在这里我们不会详细的区分析解决方案的底层&#xff01; Redis缓存概念 Redis缓存的使用&#xff0c;极大的提升了应用程序的性能和效率&#xff0c;特别是数据查询方面。但同时&#xff0c;它也带来了一些问题。其中&#xff0c;最要…

Android stdio的Gradle菜单栏无内容问题的解决方法

右边Gradle菜单栏里没有Tasks选项内容的问题 正常情况↓ 如果这个问题如果无法解决的话&#xff0c;Gradle打包就只能通过控制台输入命令来解决&#xff0c;但这无疑是把简单问题复杂化了&#xff0c;我们来看看怎么解决这个问题吧。 这里有几个方法提供&#xff0c;可以自行选…

排序篇(四)----归并排序

排序篇(四)----归并排序 1.归并(递归) 基本思想&#xff1a; 归并排序&#xff08;MERGE-SORT&#xff09;是建立在归并操作上的一种有效的排序算法,该算法是采用分治法&#xff08;Divide andConquer&#xff09;的一个非常典型的应用。将已有序的子序列合并&#xff0c;得到…

leetCode 376.摆动序列 动态规划 + 图解 + 状态转移

376. 摆动序列 - 力扣&#xff08;LeetCode&#xff09; 如果连续数字之间的差严格地在正数和负数之间交替&#xff0c;则数字序列称为 摆动序列 。第一个差&#xff08;如果存在的话&#xff09;可能是正数或负数。仅有一个元素或者含两个不等元素的序列也视作摆动序列。 例如…

微信小程序引入字体在部分机型失效不兼容解决办法

写小程序页面&#xff0c;美工作图用了特殊字体 引入代码&#xff1a; font-face {font-family: huxiaobo;src: url("https://xxxxxxxx.top/assets/fonts/huxiaobonanshenti.woff") } .font-loaded {font-family: "huxiaobo"; } 上线后发现部分安卓机型不…

209. 长度最小的子数组(滑动窗口)

一、题目 209. 长度最小的子数组 - 力扣&#xff08;LeetCode&#xff09; 二、代码 class Solution { public:int minSubArrayLen(int target, vector<int>& nums) {int left 0, right 0;int sum nums[right];int MinLength INT_MAX;while (left <nums.siz…

计算机竞赛 深度学习火车票识别系统

文章目录 0 前言1 课题意义课题难点&#xff1a; 2 实现方法2.1 图像预处理2.2 字符分割2.3 字符识别部分实现代码 3 实现效果4 最后 0 前言 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 &#x1f6a9; 图像识别 火车票识别系统 该项目较为新颖&#xff0c;适…

54、数组--模拟

LCR 146. 螺旋遍历二维数组 给定一个二维数组 array&#xff0c;请返回「螺旋遍历」该数组的结果。 螺旋遍历&#xff1a;从左上角开始&#xff0c;按照 向右、向下、向左、向上 的顺序 依次 提取元素&#xff0c;然后再进入内部一层重复相同的步骤&#xff0c;直到提取完所有…

(vue3)create-vue 组合式APIsetup、ref、watch,通信

优势&#xff1a; 更易维护&#xff1a;组合式api&#xff0c;更好的TS支持 之前是选项式api&#xff0c;现在是组合式&#xff0c;把同功能的api集合式管理 复用功能封装成一整个函数 更快的速度 更小的体积 更优的数据响应式&#xff1a;Proxy create-vue 新的脚手架工…