Mounting
getDefaultProps-->getInitialState-->componentWillMount-->render
-->componentDidMount
Updating
componentWillReceiveProps-->shouldComponentUpdate-->componentWillUpdate
-->render-->componentDidUpdate
Unmounting
componentWillUnmount
src/SayHi.js
import React, { Component } from 'react';
class SayHi extends React.Component {
constructor(props) {
super(props);
console.log('constructor');
this.handleClick = this.handleClick.bind(this);
this.state = {date: new Date()};
}
handleClick() {
this.setState({date: new Date()});
}
componentWillMount() {
console.log('componentWillMount');
}
componentDidMount() {
console.log('componentDidMount');
}
componentWillReceiveProps() {
console.log('componentWillReceiveProps');
}
shouldComponentUpdate(nextProps, nextState) {
console.log('shouldComponentUpdate');
console.log('nextProps:'+nextProps.name);
console.log('nextState:'+nextState.date);
return true;
}
componentWillUpdate() {
console.log('componentWillUpdate');
}
componentDidUpdate() {
console.log('componentDidUpdate');
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
render() {
return <h1 onClick={this.handleClick}>{this.state.date.toLocaleTimeString()} Hi, {this.props.name}</h1>;
}
}
export default SayHi;
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import SayHi from './SayHi';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<SayHi name="John" />, document.getElementById('root'));
registerServiceWorker();
console.log
constructor
componentWillMount
componentDidMount
測試請點擊"h1"元素觸發onClick事件更新畫面,shouldComponentUpdate印出nextProps和nextState,假設回傳值為false則不會更新畫面,所以在撰寫程式可在這判斷是否要更新畫面。
console.log
shouldComponentUpdate
nextProps:John
nextState:Tue Dec 26 2017 15:35:34 GMT+0800 (台北標準時間)
componentWillUpdate
componentDidUpdate