React的生命週期(新)
阿新 • • 發佈:2021-11-13
新生命週期新增的兩個鉤子:
1.getDerivedStateFromProps :罕見的使用場景,如果state 的值在任何時候都取決於 props ,可以使用這個函式。但是程式碼會冗餘,並且元件不好維護,不常使用。
2. getSnapshotBeforeUpdate :元件在更新之前來個快照。使用概率很低。
使用場景示例: 一個新聞列表固定高度,裡面的內容是動態增加的,當拖動滾動條只想停留在當前新聞時,可以用到這個鉤子。
程式碼如下:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>4. getSnapshotBeforeUpdate的使用場景</title>
</head>
<style>
.list {
width: 200px;
height: 150px;
overflow: auto;
background -color: skyblue;
}
.news {
height: 30px;
}
</style>
<body>
<div id="list"></div>
<!-- 引入react核心庫 -->
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<!-- 引入react-dom,用於支援react操作DOM -->
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<!-- 引入babel,用於將jsx轉為js -->
<script src="https://unpkg.com/[email protected]/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)
}
render() {
return (
<div className="list" ref="list">
{
this.state.newsArr.map((n, index) => {
return <div className="news" key={index}>{n}</div>
})
}
</div>
)
}
getSnapshotBeforeUpdate() {
return this.refs.list.scrollHeight
}
componentDidUpdate(preProps, preState, height) {
this.refs.list.scrollTop += this.refs.list.scrollHeight - height
}
}
ReactDOM.render(<NewsList/>, document.getElementById('list'))
</script>
</body>
</html>
效果如下圖: 滾動條一直在縮短,內容在變長,但是列表是固定的,沒有隨著滾動條滾動
總結: 1. 初始化階段: 由 ReactDOM.render() 觸發 —— 初次渲染 1. constructor() 2. getDerivedStateFromProps 3. render() 4. componentDidMount() ===> 常用 一般在這個鉤子中做一些初始化的事情。例如:開啟定時器、傳送ajax請求、訂閱訊息 2. 更新階段: 由元件內部 this.setState() 或父元件重新 render 觸發 1. getDerivedStateFromProps 2. shouldComponentUpdate() 3. render() ===> 常用 初始化渲染或更新渲染呼叫 4. getSnapshotBeforeUpdate() 5. componentDidUpdate() 3. 解除安裝元件: 由 ReactDOM.unmountComponentAtNode() 觸發 1. componentWillUnmount() ====> 常用 一般在這個鉤子中做一些收尾的事。例如:關閉定時器、取消訂閱訊息 即將廢棄的鉤子: 1. componentWillMount 2. componentWillReceiveProps 3. componentWillUpdate 現在使用會出現警告,下一個大版本需要加上UNSAFE_字首才能使用,以後可能會被徹底廢棄,不建議使用。