Each component has several "lifecycle methods" that you can override to run code at particular times in the process. Methods prefixed with will are called right before something happens, and methods prefixed with did are called right after something happens. --- React官方文檔

掛載
初始化過程如下:
- constructor
- componentWillMount
- render
- componentDidMount
更新
當(dāng)父組件給子組件傳值時,會觸發(fā)如下更新過程:
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
卸載
當(dāng)一個組件被從DOM中移除時,該方法別調(diào)用:
- componentWillUnmount
具體加載過程參考如下圖:

具體代碼
- 掛載
class CycleLife extends React.Component { // 掛載過程 // 1.構(gòu)造器函數(shù) constructor(props) { super(props); console.log('構(gòu)造器函數(shù)'); } // 2.組件將要掛載 componentWillMount() { console.log('組件將要被掛載'); } // 3.組件渲染 render() { console.log('組件被渲染'); return ( <h1>Hello, World</h1> ); } // 4.組件已經(jīng)掛載 componentDidMount() { console.log('組件已經(jīng)被掛載'); } } - state 變更觸發(fā)更新
class CycleLife extends React.Component { constructor(props) { super(props) this.state = { time: new Date() } } changeTime = () => { this.setState({ time: new Date() }) } componentDidMount() { // 每隔一秒修改時間, 實現(xiàn)時鐘效果 setInterval(this.changeTime, 1000) } // 1. 判斷是否需要組件更新, 默認(rèn) true shouldComponentUpdate(nextProps, nextState) { // 返回 false 時, 后續(xù)函數(shù)不執(zhí)行 return true } // 2. 組件將要更新 componentWillUpdate(nextProps, nextState) { console.log('nextProps: ', nextProps) console.log('nextState: ', nextState) console.log('組件將要被掛載') } // 3. 組件被重新渲染 render() { console.log('組件被重新渲染') return ( <h1>{this.state.time.toLocaleString()}</h1> ); } // 4. 組件已經(jīng)更新 componentDidUpdate() { console.log('組件已經(jīng)被掛載') } } ReactDOM.render( <CycleLife/>, document.getElementById('root') ); - 父 -> 子 傳遞屬性時, 發(fā)生的生命周期
class CycleLife extends React.Component { static propTypes = { content: React.PropTypes.string } constructor(props) { super(props) } // 1. 父 -> 子傳遞props時, 觸發(fā) componentWillReceiveProps(nextProps, nextState) { console.log('組件屬性被父級修改') console.log('nextProps: ', nextProps) console.log('nextState: ', nextState) } // 2. 判斷是否需要組件更新, 默認(rèn) true shouldComponentUpdate(nextProps, nextState) { console.log('判斷組件是否需要更新') // 返回 false 時, 后續(xù)函數(shù)不執(zhí)行 return true } // 3. 組件將要更新 componentWillUpdate(nextProps, nextState) { console.log('nextProps: ', nextProps) console.log('nextState: ', nextState) console.log('組件將要被掛載') } // 4. 組件被重新渲染 render() { console.log('組件被重新渲染') return ( <h1>{this.props.content}</h1> ); } // 5. 組件已經(jīng)更新 componentDidUpdate() { console.log('組件已經(jīng)被掛載') } } class FatherComponent extends React.Component { constructor(props) { super(props) this.state = { content: '生命周期展示' } } componentDidMount() { this.setState({ content: '生命周期展示被改變' }) } render() { return ( <CycleLife content={this.state.content}/> ) } } ReactDOM.render( <FatherComponent />, document.getElementById('root') );
文章首發(fā) learning-react,本文禁止轉(zhuǎn)載。