0206 Legacy Lifecycle-Component-React

1 Preface

The React lifecycle describes the different stages a component goes through as it is created, updated, and destroyed. These lifecycle methods can be defined and implemented in the component’s code to perform custom actions when appropriate.

Now let’s learn the life cycle functions of the old version (16.x and before), and then compare and learn the new version (17.x and later) of the statement cycle method.

The following is a diagram of the life cycle of components in React 16 and earlier versions:

2 example leads to life cycle function

The example effect is shown in Figure 1-1 below:

  • ? The transparency of the font gradually fades and repeats
  • Click the remove button to remove the component

code show as below:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>1201_export life cycle</title>
</head>

<body>
  <div id="test"></div>
  <!-- react core library -->
  <script type="text/javascript" src="../js/react.development.js"></script>
  <!-- Used to support react to operate DOM -->
  <script type="text/javascript" src="../js/react-dom.development.js"></script>
  <!-- Used to convert jsx to js -->
  <script type="text/javascript" src="../js/babel.min.js"></script>

  <script type="text/babel">

    /**
     * Create components
     * Life cycle function: life cycle hook function
     */
    class Life extends React. Component {
      // initial state
      state = {
        opacity: 1 // transparency
      }

      /**
       * remove component
       */
      remove = () => {
        // unmount the component
        ReactDOM.unmountComponentAtNode(document.getElementById('test'))
      }

      /**
       * The component is mounted
       */
      componentDidMount() {
        // Realize the effect of gradually fading the font
        this.timer = setInterval(() => {
          let {opacity} = this.state
          // After the font transparency is 0, that is, transparent, reassign 1
          if (opacity <= 0) {
            opacity = 1
          }
          opacity -= 0.1
          this. setState({opacity})
        }, 200);
      }

      /**
       * Before the component is uninstalled
       */
      componentWillUnmount() {
        // clear timer
        clearInterval(this. timer)
      }

      /**
       * Initialize rendering, state update and re-render
       */
      render() {
        return (
          <div>
            <h2 style={<!-- -->{opacity: this.state.opacity}}>Learn React component life cycle</h2><br/>
            <button onClick={this.remove}>Remove</button>
          </div>
        )
      }
      
    }

    // 2. Render the virtual DOM to the page
    ReactDOM.render(<Life/>, document.getElementById('test'))

  </script>
</body>

</html>
  • ReactDOM.unmountComponentAtNode() is the unmount component API
  • The timer is required to be created after the component is mounted, and is created once; it is cleared before the component is unmounted.
  • componentDidMount(): executed after the component is mounted
  • componentWillUnmount(): executed before the component is unmounted
  • React also provides many other lifecycle functions

Lifecycle functions are also called lifecycle hook functions, lifecycle hooks. React will call the corresponding life cycle function at the appropriate time point.

3 life cycle

The life cycle before React 16 was divided into three phases:

  • Mounting phase
  • Updating phase
  • Unmounting phase

3 mount phase

Mounting phase (Mounting): This is the process in which the component is instantiated and inserted into the DOM. At this stage, React will call the following methods in sequence:

  • constructor(): The constructor of the component, which is called when the component is created.
  • componentWillMount(): Called before the component is inserted into the DOM.
  • render(): Generate virtual DOM and return JSX.
  • componentDidMount(): Called after the component is inserted into the DOM.

The sample code is shown in 3-1 below:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>1202_Lifecycle (Old)</title>
</head>

<body>
  <div id="test"></div>
  <!-- react core library -->
  <script type="text/javascript" src="../js/react.development.js"></script>
  <!-- Used to support react to operate DOM -->
  <script type="text/javascript" src="../js/react-dom.development.js"></script>
  <!-- Used to convert jsx to js -->
  <script type="text/javascript" src="../js/babel.min.js"></script>

  <script type="text/babel">

    /**
     * Create components
     * Life cycle function: life cycle hook function
     */
    class Count extends React. Component {<!-- -->
      constructor(props) {<!-- -->
        console.log('Count === constructor');
        super(props)
        // initial state
        this.state = {<!-- -->
          count: 1 // count
        }
      }


      /**
       * + 1
       */
      add = () => {<!-- -->
        this.setState({<!-- -->count: this.state.count + 1})
      }

      /**
       * Uninstall the component
       */
       remove = () => {<!-- -->
        ReactDOM.unmountComponentAtNode(document.getElementById('test'))
      }

      /**
       * The component will be mounted
       */
      componentWillMount() {<!-- -->
        console.log('Count === componentWillMount');
      }

      /**
       * The component is mounted
       */
      componentDidMount() {<!-- -->
        console.log('Count === componentDidMount');
      }

      /**
       * Before the component is uninstalled
       */
      componentWillUnmount() {<!-- -->
        console.log('Count === componentWillUnmount');
      }

      /**
       * Initialize rendering, state update and re-render
       */
      render() {<!-- -->
        console.log('Count === render');
        const {<!-- --> count } = this.state
        return (
          <div>
            <h2>Current count: {<!-- -->count}</h2><br />
            <button onClick={<!-- -->this.add}>click me + 1</button>
          </div>
        )
      }
    }

    // 2. Render the virtual DOM to the page
    ReactDOM.render(<Count />, document.getElementById('test'))

  </script>
</body>

</html>

As shown in Figure 3-1 below:

4 update phase

During the update phase, a component’s props or state are modified, causing a re-render. Here are the lifecycle methods for the update phase:

  • componentWillReceiveProps(): Used to operate when the component receives new props. It will be called before the component receives new props, and can update the state of the component according to the new props.
  • shouldComponentUpdate(nextProps, nextState): Called when the component is updated to determine whether the component needs to be re-rendered, which can optimize performance and return true by default.
  • componentWillUpdate(): The function is to allow the component to perform some preparatory work before updating, such as calculating the value of some properties or states, or performing some necessary cleaning operations before updating the component. However, it should be noted that the state or DOM of the component cannot be directly updated in this method, because the component has not been updated at this time.
  • render(): Called when the component is updated, returns the virtual DOM for rendering to the page.
  • componentDidUpdate(prevProps, prevState, snapshot): Called after the component is updated, it can perform operations such as DOM operations or initiate network requests.

The first update, the update caused by setState()

  • The difference between shouldComponentUpdate returning true and returning false

Taking code 3-1 as an example, add the shouldComponentUpdate function code as follows;

shouldComponentUpdate(nextProps, nextState) {
  console.log('count === shouldComponentUpdate :', nextProps, '----', nextState);
  return true;
}

When true is returned, as shown in Figure 4-1 below:

When false is returned, as shown in Figure 4-2 below:

The declaration cycle function shouldComponentUpdate() returns true by default, and the life cycle functions after this method are executed normally; when false is returned, the subsequent life cycle functions are not executed.

The second update, the update after executing forceUpdate()

? Example, the above basis is adding a button, click to execute forceUpdate, sample code:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>1203_updating-life cycle (old)</title>
</head>

<body>
  <div id="test"></div>
  <!-- react core library -->
  <script type="text/javascript" src="../js/react.development.js"></script>
  <!-- Used to support react to operate DOM -->
  <script type="text/javascript" src="../js/react-dom.development.js"></script>
  <!-- Used to convert jsx to js -->
  <script type="text/javascript" src="../js/babel.min.js"></script>

  <script type="text/babel">

    /**
     * Create components
     * Life cycle function: life cycle hook function
     */
    class Count extends React. Component {
      constructor(props) {
        console.log('Count === constructor');
        super(props)
        // initial state
        this.state = {
          count: 1 // count
        }
      }


      /**
       * + 1
       */
      add = () => {
        this.setState({count: this.state.count + 1})
      }

      /**
       * Do not update status, force update
       */
      force = () => {
        console.log('Count ==== forceUpate');
        this. forceUpdate()
      }

      /**
       * Uninstall the component
       */
       remove = () => {
        ReactDOM.unmountComponentAtNode(document.getElementById('test'))
      }

      /**
       * The component will be mounted
       */
      componentWillMount() {
        console.log('Count === componentWillMount');
      }

      /**
       * The component is mounted
       */
      componentDidMount() {
        console.log('Count === componentDidMount');
      }
      
      /**
       * Whether the component should be updated
       */
      shouldComponentUpdate(nextProps, nextState) {
        console.log('count === shouldComponentUpdate :', nextProps, '----', nextState);
        return true;
      }

      /**
       * Before the component will be updated
       */
      componentWillUpdate(nextProps, nextState) {
        console.log('count === componentWillUpdate :', nextProps, '----', nextState);
      }

      /**
       * After the component will be updated
       */
       componentDidUpdate(prevProps, prevState) {
        console.log('count === componentDidUpdate :', prevProps, '----', prevState);
      }

      /**
       * Before the component is uninstalled
       */
      componentWillUnmount() {
        console.log('Count === componentWillUnmount');
      }

      /**
       * Initialize rendering, state update and re-render
       */
      render() {
        console.log('Count === render');
        const { count } = this.state
        return (
          <div>
            <h2>Current count: {count}</h2><br />
            <button onClick={this.add}>click me + 1</button><br/>
            <button onClick={this.force}>Force update without changing status</button>
            </div>
        )
      }
    }

    // 2. Render the virtual DOM to the page
    ReactDOM.render(<Count />, document.getElementById('test'))

  </script>
</body>

</html>

Click the sample effect as shown in Figure 4-3 below:

The forceUpdate() method of the execution component is not affected by the shouldComponentUpdate function.

The third type of update is the update of the child component caused by the update of the parent component in the parent-child component.

The example code is shown in the code 4-4 below:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>1204_parent-son-life cycle (old)</title>
</head>

<body>
  <div id="test"></div>
  <!-- react core library -->
  <script type="text/javascript" src="../js/react.development.js"></script>
  <!-- Used to support react to operate DOM -->
  <script type="text/javascript" src="../js/react-dom.development.js"></script>
  <!-- Used to convert jsx to js -->
  <script type="text/javascript" src="../js/babel.min.js"></script>

  <script type="text/babel">

    /**
     * Create components
     * Life cycle function: life cycle hook function
     */
    class SuperCar extends React. Component {
      state = {carName: 'The first generation of Mercedes-Benz'}

      changeCar = () => {
        this.setState({carName: '2nd generation Mercedes-Benz'})
      }
      
      

      /**
       * Initialize rendering, state update and re-render
       */
      render() {
        
        const { carName } = this.state
        return (
          <div>
            <h2>My parent component</h2><br />
            <button onClick={this.changeCar}>Change car</button><br/>
            <SubCar carName={carName}/>
            </div>
        )
      }
    }

    class SubCar extends React. Component {
      
      
      /**
       * The component will accept update props
       */
       componentWillReceiveProps(nextProps) {
        console.log('SubCar === componentWillReceiveProps', '---', nextProps);
      }
      
      /**
       * The component will be mounted
       */
       componentWillMount() {
        console.log('SubCar === componentWillMount');
      }

      /**
       * The component is mounted
       */
      componentDidMount() {
        console.log('SubCar === componentDidMount');
      }
      
      /**
       * Whether the component should be updated
       */
      shouldComponentUpdate(nextProps, nextState) {
        console.log('SubCar === shouldComponentUpdate :', nextProps, '----', nextState);
        return true;
      }

      /**
       * Before the component will be updated
       */
      componentWillUpdate(nextProps, nextState) {
        console.log('SubCar === componentWillUpdate :', nextProps, '----', nextState);
      }

      /**
       * After the component will be updated
       */
       componentDidUpdate(prevProps, prevState) {
        console.log('SubCar === componentDidUpdate :', prevProps, '----', prevState);
      }

      /**
       * Before the component is uninstalled
       */
      componentWillUnmount() {
        console.log('SubCar === componentWillUnmount');
      }

      render() {
        console.log('SubCar === render');
        return (
        <div>
          <h2>I am a subcomponent, and I receive {this.props['carName']}</h2>
         </div>
        )
      }
    }

    // 2. Render the virtual DOM to the page
    ReactDOM.render(<SuperCar />, document.getElementById('test'))

  </script>
</body>

</html>

The effect is shown in Figure 4-4 below:

componentWillReceiveProps will not be executed by default for the first time, and will only be executed when props are updated again.

5 Uninstall phase

Unmount the component through ReactDOM.unmountComponentAtNode (component), and call back the lifecycle function componentWillUnmount() before unmounting

There are examples in #2, not demonstrated here.

At present, the life cycle of the old version of React components has been explained. Let’s compare and explain the life cycle of the new version of React components.

Postscript

?QQ:806797785

Source code warehouse address: https://gitee.com/gaogzhen/react-study

refer to:

[1] Shang Silicon Valley React tutorial (2022 plus update, B station super fire react tutorial) [CP/OL]. 2020-12-15.p37-p42.

[2] React official website [CP/OL].

[2]ChatGPT[CP/OL].