React 學習筆記 (六)(生命週期)
阿新 • • 發佈:2018-11-07
<Lifecycle></Lifecycle>
元件載入時觸發的函式
constructor —> componentWillMount —> render —> componentDidMount
import React, { Component } from 'react'; class Lifecycle extends Component { constructor(props) { console.log('01建構函式') super(props); this.state = { msg:'我是msg' }; } // 資料將要掛載 componentWillMount(){ console.log('02元件將要掛載') } // 資料渲染 render() { console.log('03資料渲染render') return ( <div> <h2>生命週期 {this.state.msg}</h2> </div> ); } // 資料掛載完成 componentDidMount(){ //dom操作放在這裡 請求資料也放在這裡 console.log('04元件掛載完成') } } export default Lifecycle;
元件更新時觸發的函式
shouldComponentUpdate —> componentWillUpdate —> render —> componentDidUpdate
import React, { Component } from 'react'; class Lifecycle extends Component { constructor(props) { console.log('01建構函式') super(props); this.state = { msg:'我是msg' }; } // 是否要更新資料 返回true會更新資料 返回false不會更新資料 //nextProps 父子元件傳值時的資料 nextState改變後的資料 shouldComponentUpdate(nextProps,nextState){ console.log('01是否要更新資料') console.log(nextProps) console.log(nextState) return true } // 資料將要更新 componentWillUpdate(){ console.log('02元件將要更新') } getMsg=()=>{ this.setState({ msg:'改變msg' }) } // 資料渲染 render() { console.log('03資料渲染render') return ( <div> <h2>生命週期 {this.state.msg}</h2> <button onClick={this.getMsg}>改變msg</button> </div> ); } // 資料更新完成 componentDidUpdate(){ console.log('04元件資料更新') } } export default Lifecycle;
componentWillReceiveProps:在父元件裡面改變props傳值時觸發
componentWillReceiveProps(){
console.log('在父元件裡面改變props傳值時觸發')
}
componentWillUnmount:元件銷燬時觸發的函式 銷燬哪個寫在哪個元件裡
componentWillUnmount(){
console.log('元件銷燬')
}