回答react新旧生命周期的区别是什么

 所属分类:web前端开发

 浏览:123次-  评论: 0次-  更新时间:2022-11-03
描述:更多教程资料进入php教程获得。 react新旧生命周期的区别:1、新生命周期中去掉了三个will钩子,分别为componentWillMount、componentWillR...
更多教程资料进入php教程获得。

react新旧生命周期的区别:1、新生命周期中去掉了三个will钩子,分别为componentWillMount、componentWillReceiveProps、componentWillUpdate;2、新生命周期中新增了两个钩子,分别为getDerivedStateFromProps(从props中得到衍生的state)和getSnapshotBeforeUpdate。

前端(vue)入门到精通课程:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

本教程操作环境: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,定时新增一行,实现在新增的时候,使目前观看的行高度不变。

<!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新旧生命周期的区别是什么的详细内容,更多请关注zzsucai.com其它相关文章!

 标签: 生命周期,React,
积分说明:注册即送10金币,每日签到可获得更多金币,成为VIP会员可免金币下载! 充值积分充值会员更多说明»

讨论这个素材(0)回答他人问题或分享使用心得奖励金币

〒_〒 居然一个评论都没有……

表情  文明上网,理性发言!