您好,欢迎访问一九零五行业门户网

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

react新旧生命周期的区别:1、新生命周期中去掉了三个will钩子,分别为componentwillmount、componentwillreceiveprops、componentwillupdate;2、新生命周期中新增了两个钩子,分别为getderivedstatefromprops(从props中得到衍生的state)和getsnapshotbeforeupdate。
本教程操作环境:windows7系统、react18版、dell g3电脑。
react在版本16.3前后存在两套生命周期,16.3之前为旧版,之后则是新版,虽有新旧之分,但主体上大同小异。
react生命周期(旧)
值得强调的是:componentwillreceiveprops函数在props第一次传进来时不会调用,只有第二次后(包括第二次)传入props时,才会调用
shouldcomponentupdate像一个阀门,需要一个返回值(true or false)来确定本次更新的状态是不是需要重新render
react生命周期(新)
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新旧生命周期的区别是什么的详细内容。
其它类似信息

推荐信息