This is the 12th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

Preface * *

The life cycle of React has always been very important in our work. We often need to do what we need at the required time. In React, The life cycle can be divided into Initialization, Mounting, Updating, and Unmounting stages, each of which calls a different life cycle function. Of course, with the update of React version, there will also be relative changes, so let’s refer to the summary now

1 Initialization

Is the following code in the class constructor (constructor ()), the Test class inherits the react Component the base class, also inherited the react of the base class, to have a render (), life cycle method can be used, This is why function components cannot use these methods. Super (props) is used to call the constructor of the base class (constructor()). It is also used to inject the parent component’s props to the child component. The child component reads the props (read-only, immutable state). Constructor () is used to do some component initialization, such as defining the initial content of this.state.

Note: Constructor is not a lifecycle function. This is called constructor, which is the basic syntax for ES6. Although it has the same properties as a lifecycle function, it cannot be considered a lifecycle function. But think of it as a lifecycle function. I personally think of it as the Initialization phase of React, defining the properties and the states.

import React, { Component } from 'react'
class Test extends Component {
  constructor(props) {
  super(props)
  }
}

Copy the code

Mounting stage Mounting

  1. componentWillMount: Executes when the component is about to be mounted to the page.

This is called before the component is mounted to the DOM and will only be called once. Calling this.setState here does not cause the component to be rerendered. It is also possible to advance what is written here to constructor(), so it is rarely used in projects.

  1. render: executes when the page state or props changes.

Return a React element (describing the component, i.e. UI) based on the component’s props and state, and not responsible for the actual rendering of the component. React itself then renders the page DOM based on this element. Render is a Pure function (Pure function: the return of a function depends only on its arguments; This. SetState cannot be executed in this function, it has the side effect of changing the state of the component.

  1. componentDidMount: Executed when the component is mounted.

Called after the component is mounted to the DOM, and is called only once

export default class App extends Component {
  componentWillMount () {
    console.log('componentWillMount---- The moment a component will be mounted to a page ')}render() {
    console.log('render-- Component mounted....... ')
    return (
      <div>
        <TodoList/> 
        <ReduxTodoList/>
      </div>
    )
  }
  componentDidMount () {
    console.log('componentDidMount---- Executed when the component is mounted ')}}Copy the code

Printed results:

ComponentWillMount ---- When the component will be mounted to the page execute render---- start to mount render didmount ---- When the component is mounted complete execute this is the life cycle of the mount phase, of course it has nothing to do with the writing orderCopy the code

Note: The life cycle functions componentWillMount and componentDidMount are executed only once when the page is refreshed, while the render function is executed whenever state and props change.

Third update phase Updation

This stage is a complicated one. As can be seen from the figure above, there are two kinds of situations causing component update. It is necessary to clarify the update mechanism of React component first. SetState = props = props = props = props = props = props = props = props = props = props

  1. ShouldComponentUpdate, which is executed automatically before the component is updated, requires a Boolean to be returned. It must have a return value, so it returns a true value. If you return false, This component will not be updated. In simple terms, return true and agree to update the component. If false is returned, component updates are opposed. This method compares nextProps, nextState, and the current component’s this.props, this.state. Returning true will allow the current component to continue the update process, and false will stop the update process. This method can be used to reduce unneeded rendering of components and optimize component performance.

  2. ComponentWillUpdate before component updates, but after shouldComponenUpdate implemented, but shouldComponenUpdate returns false when the updating, will oppose this function will not perform

  3. The componentDidUpdate is executed after the component is updated. It is the last step in the component update

export default class App extends Component {
  shouldComponentUpdate () {
    console.log ('1.shouldComponentUpdate---- before component updates')
    return true
  }
  componentWillUpdate () {
    console.log ('2.com ComponentWillUpdate -- executed after shouldComponentUpdate before component update ')}render() {
    console.log('3. Render -- Component mounts render....... ')
    return (
      <div>
        <TodoList/> 
        <ReduxTodoList/>
      </div>
    )
  }
  componentDidUpdate () {
    console.log('componentDidUpdate---- Execution time when component updates are complete ')}}Copy the code

Print results and order of execution

1-shouldComponentUpdate-- execute componentWillUpdate before component changes ShouldComponentUpdate 3-render---- to start mounting rendering 4-componentDidUpdate---- To execute after component updateCopy the code
  1. So in the figure abovecomponentWillReceivePropsWhen the child receives the parameter passed by the parent, the parent render function is reexecuted, and the lifecycle is executed.

    Note:

    usecomponentWillReceivePropsThe first time a component exists in the Dom, the function is not executed.

    The function is executed only if it already exists in the Dom.

    This method takes a parameter that refers to the latest props status data passed to the component by the current parent. In this lifecycle method, we can find out whether the props have changed by comparing the values of the nextProps and this. Props and do some data processing logic in turn.

Destruction phase Unmounting

There is only one life cycle function at this stage :componentWillUnmount. This method is called before the component is unmounted. You can perform cleanup tasks such as clarifying the timer used in the component, clarifying the DOM elements manually created in componentDidMount, untying events, and so on. To avoid causing a memory leak

Summary of optimization pages using life cycle functions:

  1. incomponentDidMount(componentDidMount); (Render) (componentDidMount); When executing in componentWillMount, when using RN, there will be a conflict. It is highly recommended that you make ajax requests in componentDidMount.
  2. When the parent component is updated, it is passed to the child component, causing the pros to change. The child component’s Render function keeps triggering, causing performance problems. We can do this normally during the update phase, so we use shouldComponentUpdate
shouldComponentUpdate(nextProps,nextState){
    if(nextProps.content ! = =this.props.content){
        return true
    }else{
        return false}}Copy the code

React V16.4 life cycle

Change the reason

The original (pre-React V16.0) life cycle was not appropriate after React V16 introduced Fiber, because if async Rendering is enabled, all functions before render will be executed multiple times. What part of the original (pre-React V16.0) lifecycle was implemented before Render?

  • componentWillMount
  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate

If the developer has async Rendering enabled and makes A JAXrequest with the lifecycle methods executed in front of the render, AJAX will be unnecessarily called multiple times… Clearly not what we were hoping for. Also, no matter how fast the result is generated in componentWillMount, it will not be able to catch up with the first render, and componentWillMount will also be called (of course, maybe this is the expected result). Such IO operations would be better placed in componentDidMount.

Ban cannot use effect is better than getting developers don’t use, so in addition to shouldComponentUpdate, other all functions before the render function (componentWillMount, ComponentWillReceiveProps componentWillUpdate) are replaced by getDerivedStateFromProps.

GetDerivedStateFromProps to replace deprecate lifecycle functions with a static function getDerivedStateFromProps to force developers to perform only non-side effects before render, and only to determine the new state based on props and state

Two new lifecycle functions have been introduced:

1. getDerivedStateFromProps

GetDerivedStateFromProps will not be called if it is not raised by the parent, but if it is not raised by the parent, getDerivedStateFromProps will not be called. React V16.4 fixes this by Mounting or Updating getDerivedStateFromProps. For Updating, see the React V16.4 lifecycle diagram. GetDerivedStateFromProps (props, state) is called before the render method on component creation and update. It should either return an object to update the state, or null to update nothing

GetDerivedStateFromProps is called every time the parent raises a rendering of the current component, giving us the opportunity to adjust the new state based on the new props and the previous state. If the implementation is pure and has no side effects in one of the three deprecate lifecycle functions, you can move to getDerivedStateFromProps; If you have the misfortune to do something like AJAX, first of all reflect on why you did it, and then move to componentDidMount or componentDidUpdate. Currently, when you use the three deprecate lifecycle functions, there is a red alert in development mode requiring you to use the UNSAFE_ prefix. It’s likely to be deprecated during a major release update, so for those who are taking a chance, give it up.

2. getSnapshotBeforeUpdate

GetSnapshotBeforeUpdate () is called after render and can be read but the DOM is not available. It allows your component to capture some information (such as scroll position) from the DOM before it can change. Any value returned by this lifecycle is passed to componentDidUpdate () as a parameter. Examples from the website:

class ScrollingList extends React.Component {
  constructor(props) {
    super(props);
    this.listRef = React.createRef();
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Should we add new items to the list?
    // Capture the scroll position so that we can adjust the scroll later.
    if (prevProps.list.length < this.props.list.length) {
      const list = this.listRef.current;
      return list.scrollHeight - list.scrollTop;
    }
    return null;
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
    // If we have the snapshot value, we have added the new items.
    // Adjust scrolling so that new items don't push old items out of the view.
    // (Snapshot here is the value returned by getSnapshotBeforeUpdate)
    if(snapshot ! = =null) {
      const list = this.listRef.current; list.scrollTop = list.scrollHeight - snapshot; }}render() {
    return (
      <div ref={this.listRef}>{/ *... contents... * /}</div>); }}Copy the code

Note: When you use getDerivedStateFromProps, getSnapshotBeforeUpdate, the new Lifecycle API, and the Deprecate lifecycle function, the Deprecate lifecycle function is ignored. Will not be executed in time!