The life cycle of react components

Source: Internet
Author: User
Tags constructor json
Overview


The life cycle of react components is the process of react components from creation to extinction. It is broadly divided into three phases:


1.Mounting    component loading and initializing
2.Updating    component Updates 
3.Unmounting  component Offload
legend


life cycle function and its usage


Constructor (props, context) {...}


This function corresponds to the Getinitialstate method in the graph, because react removes the hook function from getinitialstate in the implementation of ES6, and stipulates that the state is implemented in constructor. The function is the component's constructor, which initializes the component States (state), which is called once when the component is created, and is called only once during the entire life cycle of the component. You cannot use the SetState method in a method


Componentwillmount () {...}


Called once before the component is loaded (render). Call SetState in this function, this time the render function can see the updated state, and the method is only called once in the component life cycle. In this method, you can use the Fetch asynchronous request load operation.


Componentdidmount () {...}


The component load (render) is called once, and the child component is already loaded, and refs can be used in the method. You can also use the SetState method, which is called only once in the life cycle of a component.


Componentwillreceiveprops (Nextprops) {...}


The props is passed to the child component through the parent component. When the parent component is render, the subassembly calls Componentwillreceiveprops (regardless of whether the props has an update or no data exchange between the parent and child components). This method is used to update component data. The SetState method can be used, and may be called multiple times during the lifetime of the component.


BOOL Shouldcomponentupdate (Nextprops, nextstate) {...}


Note that this method is the only life-cycle function that contains a return value, and the return value of the other function is void. After the component is loaded, shouldcomponentupdate is called to determine whether the component needs to be re-rendered after each call to SetState. Returns true by default and requires a re-render. In more complex applications, some data changes do not affect the interface display, can be judged here, optimize rendering efficiency. You cannot use the SetState function within a method.


Componentwillupdate (Nextprops, nextstate) {...}


Shouldcomponentupdate returns TRUE or the componentwillupdate is called after ForceUpdate is called. It is important to note that in this function, you cannot use This.setstate to modify the state. After this function is called, Nextprops and Nextstate are set to This.props and This.state respectively. Immediately after this function, render () is called to update the interface.


Render () {...}


Render is a component render function and cannot be used in render SetState


Componentdidupdate (prevprops,prevstate) {...}


In addition to calling Componentdidmount after the first render, all other render ends are called componentdidupdate. The SetState method cannot be used inside a function.


Componentwillunmount () {...}


Called when the component is about to unload. A listener event that is normally registered in Componentdidmount needs to be removed from the method to avoid unnecessary errors. Example


/ **
 * Life cycle function example.
 *
 * /
import React from 'react';
/ **
 * Parent component
 * /
export default class LifeCircle extends React.Component {

    constructor (props) {
        super (props);
        this.state = ({
            propsToChild: 1
        })
    }

    addCount = () => {
        this.setState ({
            propsToChild: this.state.propsToChild + 1
        })
    }

    render () {
        return (
            <div>
                <button onClick = (this.addCount)> Accumulate count value </ button>
                <LifeCircleChild currentCount = {this.state.propsToChild}> </ LifeCircleChild>
            </ div>
        )
    }
}

/ **
 * Lifecycle components
 * /
class LifeCircleChild extends React.Component {
    / **
     * Constructor, initialize state.
     * @param props
     * @return void
     * /
    constructor (props) {
        super (props);
        this.state = ({
            currentCount: props.currentCount, // count from the parent component
            width: 0, // The current document body width
            height: 0, // The current document body height
        })
    }

    / **
     * The function executed before the component render. In this function, you can perform some asynchronous requests and setState.
     * @return void
     * /
    componentWillMount () {
        // Asynchronous request, the return value is {currentCountResult: 1}
        fetch ('/ currentCount.json')
        .then ((res) => res.json ())
        .then ((json) => {
            this.setState ({
                currentCount: json.currentCountResult
            })
        });
    }

    / **
     * The component is executed after render. Usually, some listener events are registered in this method.
     * @return void
     * /
    componentDidMount () {
        // Add browser window resize listener event and notify this.onWindowResize method.
        window.addEventListener ('resize', this.onWindowResize);
    }

    / **
     * Called after the parent component renders, and re-renders the component state according to the value of the parent component.
     * @param Object nextProps [parameter object from the parent component]
     * @return void
     * /
    componentWillReceiveProps (nextProps) {
        this.setState ({
            currentCount: nextProps.currentCount
        })
    }

    / **
     * Determine if the component needs to be re-rendered. True is rendering. In this method, the component is not rendered when the count is divisible by 3.
     * @param Object nextProps [props to be rendered]
     * @param Object nextState [State to be rendered]
     * @return boolean [whether to render]
     * /
    shouldComponentUpdate (nextProps, nextState) {
        if (nextState.currentCount% 3 === 0) {
            return false;
        }
        return true;
    }


    / **
     * componentWillUpdate will be called after shouldComponentUpdate returns true or forceUpdate is called.
     * @param Object nextProps [this.props = nextProps]
     * @param Object nextState [this.state = nextState]
     * @return void
     * /
    componentWillUpdate (nextProps, nextState) {
        console.log (nextProps);
        console.log (nextState);
    }

    / **
     * Except componentDidMount is called after the first render, other componentDidUpdate is called after the render. The setState method cannot be used inside a function.
     * @param Object prevProps
     * @param Object prevState
     * @return void
     * /
    componentDidUpdate (prevProps, prevState) {
        console.log (prevProps);
        console.log (prevState);
    }

    / **
     * Called when the component is about to be uninstalled. Generally, the listening event registered in componentDidMount needs to be unregistered and deleted in this method to avoid unnecessary errors.
     * @return void
     * /
    componentWillUnmount () {
        // Cancel resize monitoring when the component is about to be destroyed
        window.removeEventListener ('resize', this.onWindowResize);
    }

    / **
     * Get the width and height of the document body when the browser window size changes.
     * @return void
     * /
    onWindowResize = () => {
        let width = document.body.offsetWidth;
        let height = document.body.offsetHeight;
        this.setState ({
            width: width,
            height: height
        })
    };

    / **
     * Render virtual dom
     * @return void
     * /
    render () {
        return (
            <div>
                <p>
                    Current count: {this.state.currentCount}
                </ p>
                <p>
                    Current document body height: {this.state.height}
                </ p>
                <p>
                    Current document body width: {this.state.width}
                </ p>
            </ div>
        )
    }
} 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.