getSnapshotBeforeUpdate钩子的使用场景
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>getSnapshotBeforeUpdate的使用场景</title>
<style>
.list{
width: 200px;
height: 150px;
background: 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 = {
newArr:[]
}
// 组件挂载完毕的钩子
componentDidMount(){
setInterval(()=>{
const {newArr} = this.state;
//模拟一条数据
const news = "新闻"+(newArr.length+1)
this.setState({
newArr:[news,...newArr]
})
},1000)
}
//在更新之前获取快照
getSnapshotBeforeUpdate(){
return this.refs.list.scrollHeight
}
//组件更新完毕的钩子
componentDidUpdate(prevProps,prevState,height){
this.refs.list.scrollTop += this.refs.list.scrollHeight - height
}
render(){
return (
<div className="list" ref="list">
{
this.state.newArr.map((n,index)=>{
return <div className="news" key={index}>{n}</div>
})
}
</div>
)
}
}
ReactDOM.render(<NewsList/>,document.getElementById("test"))
</script>
</body>
</html>