react17的版本更新了,作了一些更新,最近學習了新版的生命週期,來使用對比16.8的版本html
舊版本:react
新版本:異步
能夠看到新版的生命週期中 componentWillMount
, componentWillReceiveProps
, componentWillUpdate
三個生命週期被幹掉了,其實還沒被幹掉,使用時會報警告:(componentWillReceiveProps也同樣的警告)async
爲啥推薦加 UNSAFE_
前綴,官方說明:新生命週期差別
目的是爲了react18版本的 異步渲染更新
,請移步官方去查看具體:異步渲染更新新特性探索函數
新生命週期裏面,有兩個函數 getDeriveStateFromProps
,getSnapshotBeforeUpdate
學習
從props獲取一個派生的狀態,在調用 render 方法以前調用,函數必須返回一個狀態對象或者 null
,動畫
// 使用方法,必須加 static !!! static getDerivedStateFromProps(props, state)
若是在 getDerivedStateFromProps 中返回了一個狀態對象(跟定義的state中同樣),視圖中的值會被函數返回值攔截並賦值爲當前函數返回的狀態對象中的值,而且對state內容操做,視圖也不會更新(卸載組件仍是沒影響)。this
使用不多spa
// state的值跟隨props值變動而變動 // 例如判斷props內值是奇數仍是偶數,來肯定用state仍是用props // 官方舉例實現 <Transition> 組件很容易,跟隨信息判斷哪些組件作動畫 static getDerivedStateFromProps(props, state) { props.xx === xx ? props : state; }
獲取更新前的快照,從 DOM 中捕獲一些信息(例如,滾動位置)。今生命週期的任何返回值將做爲參數傳遞給 componentDidUpdate()
。應返回 snapshot
的值(或 null
)code
什麼是 snapshot
??
答案是什麼均可以!!!靈活的js,哈哈哈
結合上述,咱們的 componentDidUpdate()
方法中的參數就應該是 prevProps
, prevState
來個例子,滾動位置定位
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(prevProps, prevState, height){ // 計算滾動到當前想顯示的條目位置而且保持不動 // height就是咱們說的 snapshot 的值!!!! 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'))