react 生命週期之 更新階段
阿新 • • 發佈:2021-06-10
class Child3 extends Component{ state = { count:1 } static getDerivedStateFromProps(props, nextState) { console.log(1,"將props中的資料對映到state中",props); return props;//返回值 ,是根據props 要對映到state中的值 } shouldComponentUpdate(nextProps, nextState) { console.log("props",this.props,nextProps); console.log("state", this.props, nextState); console.log(2,"判斷當前元件是否需要更新"); return true;//true 繼續完成當前元件更新,false 中斷當前元件更新 } //獲取更新前的DOM快照 必需加上componentDidUpdate getSnapshotBeforeUpdate(prevProps, prevState) { console.log(4,"獲取DOM更新前的快照");//已經構建好新的虛擬DOM即將去更新真實DOM return document.querySelector("#info").innerHTML; } //處理副作用(請求) prevDom=getSnapshotBeforeUpdate return componentDidUpdate(prevProps, prevState, prevDom) { console.log(5,"元件列新完成",prevDom); } render() { console.log(3,"構建虛擬DOM"); const { count,parentInfo}= this.state; return <> <p id="info">count:{count}------parentInfo:{parentInfo}</p> <button onClick={ () => { this.setState({ count:count+1 }) } } > 遞增count</button> </> } }