发布时间:2025-12-10 22:47:43 浏览次数:1
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,定时新增一行,实现在新增的时候,使目前观看的行高度不变。
<!DOCTYPEhtml><html><head><metacharset="UTF-8"><title>4_getSnapShotBeforeUpdate的使用场景</title><style>.list{width:200px;height:150px;background-color:skyblue;overflow:auto;}.news{height:30px;}</style></head><body><!--准备好一个“容器”--><pid="test"></p><!--引入react核心库--><scripttype="text/javascript"src="../js/17.0.1/react.development.js"></script><!--引入react-dom,用于支持react操作DOM--><scripttype="text/javascript"src="../js/17.0.1/react-dom.development.js"></script><!--引入babel,用于将jsx转为js--><scripttype="text/javascript"src="../js/17.0.1/babel.min.js"></script><scripttype="text/babel">classNewsListextendsReact.Component{state={newsArr:[]}componentDidMount(){setInterval(()=>{//获取原状态const{newsArr}=this.state//模拟一条新闻constnews='新闻'+(newsArr.length+1)//更新状态this.setState({newsArr:[news,...newsArr]})},1000);}getSnapshotBeforeUpdate(){returnthis.refs.list.scrollHeight}componentDidUpdate(preProps,preState,height){this.refs.list.scrollTop+=this.refs.list.scrollHeight-height}render(){return(<pclassName="list"ref="list">{this.state.newsArr.map((n,index)=>{return<pkey={index}className="news">{n}</p>})}</p>)}}ReactDOM.render(<NewsList/>,document.getElementById('test'))</script></body></html>说明:
在React v16.3中,迎来了新的生命周期改动。旧的生命周期也在使用,不过在控制台上可以看到弃用警告了。并且提示有三个生命周期钩子将会被弃用,尽量不要使用。再或者可以在其前边加前缀 UNSAFE_。
读到这里,这篇“react新旧生命周期的区别有哪些”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注本站行业资讯频道。