The life cycle

  1. The life cycle is the process from component creation to destruction.
  2. When a component instance is created and inserted into the DOM, the function that needs to be called is the lifecycle function.
  3. That is, before and after a component is loaded, the component updates its data, and the component is destroyed.

1. Phase 1 — Initialization phase

Components are created until they are first rendered to the page

  1. constructor()Constructor, which is called once when the component is created
  2. componentWillMount()Called once when the component is about to be mounted
  3. render()Apply colours to a drawing
  4. componentDidMount()Called once when the component has been mounted, you can use the refs property here because the component has already been rendered.
  5. code
class App extends React.Component{ constructor(props) { super(props); // this. State = {} Initializes a state this.state = {a: props. Title, b: this.props.title }; console.log('01- constructor 1 ' );
    }
    
    componentWillMount() {
        console.log('02- Component about to be mounted 2'); // You can't do dom manipulation, // this.setState() this.state this.props are all asynchronous this.setState({c:'Requested data'
        });
        console.log(this.state.c); //undefined
        setTimeout(()=>{ console.log( this.state.c ); // Request data},2000); }render() {
        console.log( '03- Start rendering component 3'//console.log(this.state.c)return(<div> {this.state.a} <hr /> {this.state.b} <button ref={BTN =>this._btn= BTN} onClick={this.handleclick} > </button> </div> ); }componentDidMount() {// You can see the data on the web page (picture text) // the real scene will be in this request back-end data interface // the data will be mounted to the state inside // the advantage of the state inside // 1. // 2. State data is reactive, and when the data changes, the render function console.log() is automatically triggered.'04- Component mount complete 4');
        console.log( this._btn );
        this._btn.style.background = 'skyblue'; }}; ReactDOM.render( <App title={'Pass value to App component'}></App>,
    document.querySelector('#app'));Copy the code

Print order:

  1. Undefined is printed in componentWillMount(), setState is updated with undefined, indicating that the method is asynchronous, so the timer is used, and two seconds later the value is printed out.
  2. Now that the componentDidMount() component is loaded, you can manipulate the DOM node, so you can get the Button button

Demo: Click on the current component element to execute the current event function to update the current component data b, which automatically triggers the render data

class App extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
           a: props.title,
           b: this.props.title
        };
        console.log( '01- constructor 1 ' );
    }
    
    componentWillMount() {
        console.log('02- Component about to be mounted 2');
        this.setState({
            c: 'Requested data'
        });
        console.log(this.state.c); 
        setTimeout(()=>{ console.log( this.state.c ); }, 2000); } handleClick = ()=>{ this.setState({ b:'Click event changes B's data'})}render() {
        console.log( '03- Start rendering component 3' )
        //console.log( this.state.c )
        return(<div> {this.state.a} <hr /> {this.state.b} <button ref={BTN =>this._btn= BTN} onClick={this.handleclick} > </button> </div> ); }componentDidMount() {
        console.log('04- Component mount complete 4');
        this._btn.style.background = 'skyblue'; }}; ReactDOM.render( <App title={'Pass value to App component'}></App>,
    document.querySelector('#app'));Copy the code

Click on the front:

When state is updated, render() is retriggered;


2. Phase 2 — Update phase

Changes caused by status updates

  1. The updating will trigger componentWillReceiveProps (nextProps) father child components of the function

  2. ShouldComponentUpdate (nextProps, nextState) return false/true Whether to render again. False blocks the render call

  3. ComponentWillUpdate (nextProps, nextState) is about to be updated. Properties and status cannot be modified. It is used for log printing and data obtaining

  4. Render () rendering

  5. ComponentDidUpdata () completes the update

  6. Parameters:

    NextState: indicates the current status of the child component. 2Copy the code
  7. code

// List class extends React.Component {constructor() {
        super();
        console.log( '02- Constructor 01' );
    }

    componentWillReceiveProps(nextProps) {
        console.log('02- Get data when parent component updates 02 ',nextProps);
    }
    
    shouldComponentUpdate(nextProps, nextState) { 
        console.log('02- Will component 03 be updated in the future? ');
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
        console.log('02- Components about to be updated 04', nextProps, nextState ); // Look at your requirements}render() {
        console.log('02- Render Components 05');
        return<div> <h2> This is the List component </h2> </div> } componentDidUpdate(prevProps, prevState) { console.log('02- Component update completed 06', prevProps,prevState )
    }

    componentWillUnmount() {
        console.log('03-List component about to be destroyed 07'}} // Constructor (props) {super(props); console.log('01- constructor 1 ' );
        this.state = {
            p: 'App',
            onOff: true
        };
    }
    componentWillMount() {
        console.log('01- Component about to be mounted 2');
    }
    componentDidMount() {
        console.log('01- Component mount complete 4');
    }
    render() {
        console.log( '01- Start rendering component 3' );
        return (
            <div>
                <h1>App</h1>
                <List title={this.state.p}></List>
            </div>
        );
    }
}
ReactDOM.render(
    <App></App>,
    document.querySelector('#app'));Copy the code

Effect:

  1. Since List is a sub-component of App, App render will render the List as well, so it will print “02- constructor 01”, and List will render as well, it will print “02- render component 05”, and then the component will load.
  2. ComponentWillReceiveProps () is in the update the data when the parent component will be triggered, the next example.

Sets methods for clicking events that modify the parent component’s data and trigger the update phase

class List extends React.Component {
    constructor(props) {
        super(props);
        //console.log( '02- Constructor 01' );
        this.state = {
            list: 'This is the list data'Title: this.props. Title}; console.log(this.state.title); } componentWillReceiveProps(nextProps) { console.log('02- Get data when parent component updates 02 ',nextProps);
    }
    
    shouldComponentUpdate(nextProps, nextState) { 
        console.log('02- Will component 03 be updated in the future? ',nextProps, nextState);
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
        console.log('02- Components about to be updated 04', nextProps, nextState ); // Look at your requirements}render() {
        console.log('02- Render Components 05');
        returnThis is the List component </h2> {this.state.title} </div>. } componentDidUpdate(prevProps, prevState) { console.log('02- Component update completed 06'PrevProps,prevState)}} // Constructor (props) {super(props); this.state = { p :"abc"
        };
    }
   
    handleClick = () =>{
        this.setState({
            p : "Click event changes App data."})}render() {
        
        return(<div> <h1>App</h1> <List title={this.state.p}></List> <button onClick={this.handleclick}></ div>); } } ReactDOM.render( <App ></App>, document.querySelector('#app'));Copy the code

Click the effect picture;

By the printing result, componentWillReceiveProps () method to get the parent group will update the data, but the page hasn’t changed, that is to say, child components of data did not update, at this time through shouldComponentUpdate update () method.

Code analysis: determine whether the title attribute of the current child component is the same as the array passed by the parent component, if not, go to if judgment, update the data, because the data is updated, so it will trigger the render method again, update the page

shouldComponentUpdate(nextProps, nextState) {
    if( this.state.title ! == nextProps.title){ this.setState({ title : nextProps.title }) };return true;
}
Copy the code

Click the effect:

. The third stage — destruction stage

Components before destruction

  1. componentWillUnmount()Component about to be destroyed

conclusion

The initialization and destruction phases occur only once in the lifetime of the component and the update phase is performed with each update to the component