我是靠谱客的博主 踏实玫瑰,这篇文章主要介绍react新旧生命周期的区别是什么,现在分享给大家,希望可以做个参考。

本教程操作环境:Windows7系统、react18版、Dell G3电脑。

react在版本16.3前后存在两套生命周期,16.3之前为旧版,之后则是新版,虽有新旧之分,但主体上大同小异。

React生命周期(旧)

1.png

值得强调的是:componentWillReceiveProps函数在props第一次传进来时不会调用,只有第二次后(包括第二次)传入props时,才会调用

shouldComponentUpdate像一个阀门,需要一个返回值(true or false)来确定本次更新的状态是不是需要重新render

React生命周期(新)

2.png

react新旧生命周期的区别

新的生命周期去掉了三个will钩子,分别是:componentWillMount、componentWillReceiveProps、componentWillUpdate

新的生命周期新增了两个钩子,分别是:

1、getDerivedStateFromProps:从props中得到衍生的state

  • 接受两个参数:props,state

  • 返回一个状态对象或者null,用来修改state的值。

  • 使用场景:若state的值在任何时候都取决于props,那么可以使用getDerivedStateFromProps

2、getSnapshotBeforeUpdate:在更新前拿到快照(可以拿到更新前的数据)

在更新DOM之前调用

返回一个对象或者null,返回值传递给componentDidUpdate

componentDidUpdate():更新DOM之后调用

  • 接受三个参数:preProps,preState,snapshotValue

使用案例:

固定高度的p,定时新增一行,实现在新增的时候,使目前观看的行高度不变。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>4_getSnapShotBeforeUpdate的使用场景</title> <style> .list{ width: 200px; height: 150px; background-color: skyblue; overflow: auto; } .news{ height: 30px; } </style> </head> <body> <!-- 准备好一个“容器” --> <div id="test"></div> <!-- 引入react核心库 --> <script type="text/javascript" src="../js/17.0.1/react.development.js"></script> <!-- 引入react-dom,用于支持react操作DOM --> <script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script> <!-- 引入babel,用于将jsx转为js --> <script type="text/javascript" src="../js/17.0.1/babel.min.js"></script> <script type="text/babel"> class NewsList extends React.Component{ state = {newsArr:[]} componentDidMount(){ setInterval(() => { //获取原状态 const {newsArr} = this.state //模拟一条新闻 const news = '新闻'+ (newsArr.length+1) //更新状态 this.setState({newsArr:[news,...newsArr]}) }, 1000); } getSnapshotBeforeUpdate(){ return this.refs.list.scrollHeight } componentDidUpdate(preProps,preState,height){ this.refs.list.scrollTop += this.refs.list.scrollHeight - height } render(){ return( <div className="list" ref="list"> { this.state.newsArr.map((n,index)=>{ return <div key={index} className="news">{n}</div> }) } </div> ) } } ReactDOM.render(<NewsList/>,document.getElementById('test')) </script> </body> </html>
登录后复制

说明:

在React v16.3中,迎来了新的生命周期改动。旧的生命周期也在使用,不过在控制台上可以看到弃用警告了。并且提示有三个生命周期钩子将会被弃用,尽量不要使用。再或者可以在其前边加前缀 UNSAFE_

【相关推荐:Redis视频教程】

以上就是react新旧生命周期的区别是什么的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是踏实玫瑰最近收集整理的关于react新旧生命周期的区别是什么的全部内容,更多相关react新旧生命周期内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(87)

评论列表共有 0 条评论

立即
投稿
返回
顶部