The lifecycle of the component

Today you learned about component life cycles

understand

  • Lifecycle callback function <=> Lifecycle hook function <=> Lifecycle function <=> Lifecycle hook
  1. The specific stages that a component goes through from creation to death
  2. The React component contains a series of hook functions (lifecycle callbacks) that are called at specific times
  3. When we define a component, we do specific work in specific lifecycle callbacks.

1. Mounting and unmounting components

Let’s start with births and deaths — mounts and unmounts.

(1) Set a timer for the Clock component when it is first rendered into the DOM. This is called “mount” in React. (2) Also, when the Clock component is removed from the DOM, the timer should be cleared. This is called “unmount” in React. Life instances call componentDidMount() when the component is mounted, and componentWillunmount() when the component is about to be unmounted.

This demo shows how to mount and uninstall components:

This is a demo using a class-like component. The text on the page will change as soon as you enter the page (mount the component), and it will disappear when you click the “Hello” button (uninstall the component).

  1. First of all,Note the position of the timer: First create a component, by changing the statestatetheopacityAt every changestateIs called oncerenderThe function. If the timer is set torenderThis will cause the transparency to change faster and faster (timer stack), and we need to use the function called after the mount is completecomponentDidMount().
  2. The next step is to add functionality to the button, so that it is called when clickeddeathThis function is going touninstallThis component, before this, we should have cleared the timer first (the component does not exist, so there is no need for the timer). At this point we can callcomponentWillunmountFunction (which is called when the component is about to be unloaded), or the clear timer statement is placed inReactDOM.unmountComponentAtNodeIt was possible before.
state = { opacity: 1 }
componentDidMount() {
        this.timer = setInterval(() = > {
            let { opacity } = this.state;
            opacity -= 0.1;
            if (opacity <= 0) opacity = 1;
            this.setState({ opacity });
        }, 200);
    }
    componentWillunmount() {
        clearInterval(this.timer);
    }
    death = () = > {
        ReactDOM.unmountComponentAtNode(document.getElementById('test'));
    }
Copy the code

ReactDOM. UnmountComponentAtNode used to uninstall the component on a node. With this small demo, you can understand the actual application of mounting and unmounting. Lifecycle functions are often called in an order that does not matter.

Now it’s time to learn about the life cycle!

2. Life Cycle (old)

The idea here is very clear. Note that each setState is called once, but not just render, shouldComponentUpdate and componentWillUpdate are also called again. ShouldComponentUpdate determines whether the component should be updated. It returns true by default. If you manually change its return value to false, the valve is closed and the component is not updated. However, if forceUpdate() is called, it is not affected by the return value (valve) of shouldComponentUpdate.

The parent component render

The parent component of this code is A and the child component is B. Render B by adding to the parent’s render value. The child component is affected by the parent component (passing values).

class A extends React.Component {
    state = { str: 'A' };
    changeStr = () = > {
        this.setState({ str: 'B'})}render() {
        return (
            <div>
                <div>A component (parent)</div>
                <button onClick={this.changeStr}>change</button>
                <B str={this.state.str} />
            </div>)}}class B extends React.Component {
    componentWillReceiveProps(props) {
        console.log('B_componentWillReceiveProps', props);
    }
    render() {
        return (
            <div>{this.props. STR}</div>
        )
    }
}
ReactDOM.render(<A />.document.getElementById('test'));
Copy the code

Realized effect:

ComponentWillReceiveProps when first entered the page is not call, click the button after (i.e., the parent component again call render), < B STR = {this. State. The STR} / > the statement to perform, Will call componentWillReceiveProps.

Summarizing the life cycle (old)

Three phases of the life cycle

(1) Initialization phase: triggered by reactdom.render () — the first rendering

  1. constructor()

  2. componentWillMount()

  3. render()

  4. ComponentDidMount () – commonly used

    It is typically initialized in this hook. For example, start the timer, send network request u, and subscribe messages.

(2) Update phase: triggered by this.setsate () or parent rerender within the component

  1. shouldComponentUpdate()Forcing an update is all about missing this link
  2. componentWillUpdate()
  3. render()Will use
  4. componentDidUpdate()

(3) unload components: by ReactDOM unmountComponentAtNode triggered () 1. ComponentWillUnmount () – used generally 1 do finishing touches in the hook. For example, disable the timer and unsubscribe messages.

3. Life Cycle (New)

The difference between the old and new version lifecycles

New version and old version of life cycle, (the) enabled componentWillMount, componentWillReceiveProps, componentWillUpDate these three functions, if you want to use, need to add the UNSAFE prefix. Also, for the new version lifecycle, there are two more functions, getDerivedStateFromProps for mount and update, and getSnapshotBeforeUpdate between Render and componentDidUpdate.

Here’s what we can see in the React document. If we are using a new version of the dependency package, the following functions are not prefixed with the UNSAFE prefix, then the Waring warning will appear.

Here are two new functions in the new version:

  • getDerivedStateFromProps()(Rarely): gets a derived state. Need to usestaticYou need to return a state objectstate objornull; Can receive an argumentpropsAnd return it. If I call this function,stateThe value of at any time depends onprops, which cannot be changed by initialization or modification. Usage scenario: State depends on props at all times.

However, derived state leads to code redundancy and makes components difficult to maintain

static getDerivedStateFromProps(props, state) {
    console.log(props, state);  // This state initializes the state property and property value
    return props;
}
ReactDOM.render(<Count count="100" />.document.getElementById('test'));
Copy the code
  • GetSnapshotBeforeUpdate () is used with componentDidUpdate, called before the last rendered output, to allow the component to capture some information from the DOM (such as scroll position) before changes are made. Any return value from this life cycle is passed to componentDidUpdate() as a parameter

    // Save a copy of the page before the effect appears
    getSnapshotBeforeUpdate() {
        console.log("getSnapshotBeforeUpdate");
        return 'mannqo'
    }
    componentDidUpdate(preProps, preState, snapshowValue) {
        console.log('componentDidUpdate', preProps, preState, snapshowValue);
    }
    Copy the code

    Application scenarios: The content is constantly updated to render as you get the result of its rendering at a given moment. If you want the scroll bar to stop scrolling, use getSnapshotBeforeUpdate(). If you want the scroll bar to stop scrolling, use getSnapshotBeforeUpdate().

conclusion

Important hooks:

  1. render: Initialize the render or update the render call
  2. componentDidMount: Starts listening and sendingajaxrequest
  3. componentWillUnmountDo some finishing touches, such as clearing the timer

That’s all for today’s study! Keep going tomorrow