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_
。
通过以上内容的阐述,相信大家对“react新旧生命周期有什么区别呢?”已经有了进一步的了解,更多相关的问题,欢迎关注网络或到官网咨询客服。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: react新旧生命周期有什么区别呢?
本文地址: https://pptw.com/jishu/653834.html