react学习笔记(8)生命周期回顾与再认识
生命周期
1.第一階段--初始化階段
組件創建到首次渲染到頁面
打印的順序:
解析:demo :點擊當前組件的元素執行當前的事件函數更新當前的組件數據b,數據變化就是自動觸發render數據
class App extends React.Component{constructor(props) {super(props);this.state = {a: props.title,b: this.props.title};console.log( '01-構造函數1 ' );}componentWillMount() {console.log('02-組件即將被掛載2');this.setState({c: '請求的數據'});console.log(this.state.c); setTimeout(()=>{console.log( this.state.c ); },2000);}handleClick = ()=>{this.setState({b: '點擊事件改變了b的數據'})}render() {console.log( '03-開始渲染組件3' )//console.log( this.state.c )return (<div>{this.state.a}<hr />{this.state.b}<buttonref={btn=>this._btn=btn}onClick={this.handleClick}>點擊 </button></div>);}componentDidMount() {console.log('04-組件掛載完成啦4');this._btn.style.background = 'skyblue';} };ReactDOM.render(<App title={'傳值給App組件'}></App>,document.querySelector('#app') ); 復制代碼點擊前:
點擊后:當更新state的時候,會重新觸發render();
2.第二階段--更新階段
狀態更新引起的變化
componentWillReceiveProps(nextProps) 父組件的更新會觸發子組件的這個函數
shouldComponentUpdate(nextProps, nextState) return false/true 是否需要重新渲染,默認值為true,表示更新;false會阻止render調用
componentWillUpdate(nextProps, nextState) 即將更新,不能修改屬性與狀態,用于日志打印和數據獲取
render() 渲染
componentDidUpdata() 完成更新
參數:
1. nextProps:父組件更新的時候帶來的數據 2. nextState:子組件當前的狀態 復制代碼代碼
效果圖:
分析:設置點擊事件,修改父組件的數據,觸發更新階段的方法
class List extends React.Component {constructor(props) {super(props);//console.log( '02-構造函數01' );this.state = {list: '這是list數據',//接收父組件傳來的值title : this.props.title};console.log(this.state.title);}componentWillReceiveProps(nextProps) {console.log('02-獲取父組件更新的時候帶來的數據02 ',nextProps);}shouldComponentUpdate(nextProps, nextState) { console.log('02-是否將來更新組件03',nextProps, nextState);return true;}componentWillUpdate(nextProps, nextState) {console.log('02-組件即將被更新04', nextProps, nextState );// 看自己的需求}render() {console.log('02-渲染組件05');return (<div><h2> 這是List組件 </h2>{this.state.title}</div>);}componentDidUpdate(prevProps, prevState) {console.log( '02-組件更新完成啦06', prevProps,prevState )} }//父組件App class App extends React.Component{constructor(props) {super(props);this.state = {p : "abc"};}handleClick = () =>{this.setState({p : "點擊事件改變了App的數據"})}render() {return (<div><h1>App</h1><List title={this.state.p}></List><button onClick={this.handleClick}>點擊事件</button></div>);} } ReactDOM.render(<App ></App>,document.querySelector('#app') ); 復制代碼點擊后的效果圖;
由打印的結果可知,componentWillReceiveProps()方法得到父組將更新的數據,可是頁面上并沒有改變,也就是說子組件的數據并沒有更新,此時通過shouldComponentUpdate()方法更新。
代碼分析:
判斷當前子組件的title屬性是否與父組件傳來的數組相同,如果不同,走if判斷,更新數據,因為數據更新了,所以會再次觸發render方法,更新頁面
點擊后的效果:
.第三階段--銷毀階段
組件在銷毀之前
總結
初始化和銷毀階段在組件的整個生命周期中只會出現一次
更新階段會在組件每次更新中都會執行
轉載于:https://juejin.im/post/5c21b20d6fb9a049e93cc0b9
總結
以上是生活随笔為你收集整理的react学习笔记(8)生命周期回顾与再认识的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 专注创新型蛋白工具研发,上海恺佧生物科技
- 下一篇: ElasticSearch PPT-笔记