首页 技术 正文
技术 2022年11月19日
0 收藏 332 点赞 2,510 浏览 1225 个字

React生命周期图解:

一、旧版图解:

React生命周期详解

二、新版图解:

React生命周期详解

从图中,我们可以清楚知道React的生命周期分为三个部分:  实例化、存在期和销毁时。

旧版生命周期如果要开启async rendering,在render函数之前的所有函数,都有可能被执行多次。

旧版的React生命周期看图就可以啦,我们就不详细讲解了,下面我们来详细讲下,V16.4React的生命周期。

由图中可以看到,React生命周期新引入了两个生命周期函数:getDerivedStateFromProps,    getSnapShotBeforeUpdate。

getDerivedStateFromProps:

getDerivedStateFromProps无论是Mounting还是Updating,也无论是因为什么引起的Updating,全部都会被调用。

getSnapshotBeforeUpdate:

getSnapshotBeforeUpdate()被调用于render之后,可以读取但无法使用DOM的时候。它使您的组件可以在可能更改之前从DOM捕获一些信息(例如滚动位置)。此生命周期返回的任何值都将作为参数传递给componentDidUpdate()。

React官网中getSnapshotBeforeUpdate的例子:

class ScrollingList extends React.Component {
constructor(props) {
super(props);
this.listRef = React.createRef();
} getSnapshotBeforeUpdate(prevProps, prevState) {
// 我们是否要添加新的 items 到列表
// 捕捉滚动位置,以便我们可以稍后调整滚动
if (prevProps.list.length < this.props.list.length) {
const list = this.listRef.current;
return list.scrollHeight - list.scrollTop;
}
return null;
} componentDidUpdate(prevProps, prevState, snapshot) {
// 如果我们有snapshot值, 我们已经添加了 新的items
// 调整滚动以至于这些新的items 不会将旧items推出视图
// (这边的snapshot是 getSnapshotBeforeUpdate方法的返回值)
if (snapshot !== null) {
const list = this.listRef.current;
list.scrollTop = list.scrollHeight - snapshot;
}
} render() {
return (
<div ref={this.listRef}>{/* ...contents... */}</div>
);
}
}

这篇文章对React生命周期的讲解就到这里啦,可以前往React官网深入学习。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,996
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,510
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,353
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,137
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848