React new version life cycle hook function and usage detailed explanation

React new version life cycle hook function and usage detailed explanation

Compared with the old life cycle

insert image description here

Three hooks are being abandoned, and two new hooks have been added

After React16, three lifecycles are deprecated (but not deleted)

  • componentWillMount (the hook where the component will be mounted)
  • componentWillReceiveProps (a hook when a component is about to receive a new parameter)
  • componentWillUpdate (the hook when the component is about to be updated)

New hooks added to the lifecycle of the new version

  • getDerivedStateFromProps
  • New properties and states can be obtained through parameters
  • This function is static
  • The return value of this function will overwrite the component state

getSnapshotBeforeUpdate

  1. The actual DOM construction is completed, but it has not yet been actually rendered to the page.
  2. In this function, it is usually used to implement some additional DOM operations
  3. The return value of this function will be used as the third parameter of componentDidUpdate

getDerivedStateFromProps

getDerivedStateFromProps is not for instances, it needs to be defined as a static method. And need to give a return value


The return value can be state Obj or null
If the return value is state Obj, the previous one will be overwritten and cannot be changed. Returning null will have no effect on any other functions.

//Get a derived state from props static getDerivedStateFromProps(props,state){
	return props
}

If the value of state depends on props at all times, you can use getDerivedStateFromProps

insert image description here

<div id="test"></div>
  <!-- Import react core library -->
  <script src="../js/17.0.1/react.development.js"></script>
  <!-- Introduce react-dom to support react to operate dom -->
  <script src="../js/17.0.1/react-dom.development.js"></script>
  <!-- Introduce babel to convert jsx to js -->
  <script src="../js/17.0.1/babel.min.js"></script>

  <script type='text/babel'>
    // Create component class Count extends React.Component{
    // Constructor constructor(props){
      console.log('Count ---constructor')
      super(props)
      // Initialize state this.state = {count:0}
    }

    //Hook componentDidMount(){
      console.log('Count --- componentDidMount')
    }

    // Uninstall component button callback death=()=>{
      ReactDOM.unmountComponentAtNode(document.getElementById('test'))
    }

    // Implement +1
     add =()=>{
      // Get the original state const {count} = this.state
      // Update status this.setState({count:count+1})
    }

    // Callback for the forced update button force=()=>{
      this.forceUpdate()
    }

    static getDerivedStateFromProps(props,state){
      console.log('getDerivedStateFromProps', props, state)
      return props
    }

    // Control component update valve shouldComponentUpdate(){
      console.log('Count --- shouldComponentUpdate')
      // If the return value is false, the valve is closed by default.
      return true
    }

    //Component update completed hook componentDidUpdate(){
      console.log('Count --- componentDidUpdate')
    }

     // The component will be uninstalled hook componentWillUnmount(){
      console.log('Count --- componentWillUnmount');
    }

    render(){
      console.log('Count --- render')
      const {count} = this.state
      return(
        <div>
          <h2>Current sum: {count}</h2>
          <button onClick={this.add}>Click me +1</button>  
          <button onClick={this.death}>Click me to uninstall the component</button>  
          <button onClick={this.force}>Click here to force update (without changing data)</button>  
        </div>
      )
    }
  }
  
  // Rendering component ReactDOM.render(<Count count={166}/>,document.getElementById('test'))
  </script>

Execution Results

insert image description here

getSnapshotBeforeUpdate

The return value can be null or a snapshot. If it is null, it has no effect. If it is a snapshot, the return value can be passed to the third parameter of componentDidUpdate.
The three parameters that componentDidUpdate can receive are the previous props, the previous state, and the snapshot returned by getSnapshotBeforeUpdate.
prevprops, prevstate, snapshotValue

insert image description here

<div id="test"></div>
  <!-- Import react core library -->
  <script src="../js/17.0.1/react.development.js"></script>
  <!-- Introduce react-dom to support react to operate dom -->
  <script src="../js/17.0.1/react-dom.development.js"></script>
  <!-- Introduce babel to convert jsx to js -->
  <script src="../js/17.0.1/babel.min.js"></script>

  <script type='text/babel'>
    // Create component class Count extends React.Component{
    // Constructor constructor(props){
      console.log('Count ---constructor')
      super(props)
      // Initialize state this.state = {count:0}
    }

    //Hook componentDidMount(){
      console.log('Count --- componentDidMount')
    }

    // Uninstall component button callback death=()=>{
      ReactDOM.unmountComponentAtNode(document.getElementById('test'))
    }

    // Implement +1
     add =()=>{
      // Get the original state const {count} = this.state
      // Update status this.setState({count:count+1})
    }

    // Callback for the forced update button force=()=>{
      this.forceUpdate()
    }

    static getDerivedStateFromProps(props,state){
      console.log('getDerivedStateFromProps', props, state)
      return null
    }

    getSnapshotBeforeUpdate(){
      console.log('getSnapshotBeforeUpdate');
      return "eee"
    }

    // Control component update valve shouldComponentUpdate(){
      console.log('Count --- shouldComponentUpdate')
      // If the return value is false, the valve is closed by default.
      return true
    }

    //Component update completed hook componentDidUpdate(preProps,preState,snapshotValue){
      console.log('Count---1componentDidUpdate',preProps,preState,snapshotValue);
    }

     // The component will be uninstalled hook componentWillUnmount(){
      console.log('Count --- componentWillUnmount');
    }

    render(){
      console.log('Count --- render')
      const {count} = this.state
      return(
        <div>
          <h2>Current sum: {count}</h2>
          <button onClick={this.add}>Click me +1</button>  
          <button onClick={this.death}>Click me to uninstall the component</button>  
          <button onClick={this.force}>Click here to force update (without changing data)</button>  
        </div>
      )
    }
  }
  
  // Rendering component ReactDOM.render(<Count count={166}/>,document.getElementById('test'))
  </script>

Summarize

Three Phases of the Life Cycle (New)

1. Initialization phase: triggered by ReactDOM.render() - initial rendering

constructor()getDerivedStateFromPropsrender()componentDidMount()

2. Update phase: triggered by this.setSate() inside the component or re-rendering of the parent component

getDerivedStateFromPropsshouldComponentUpdate()render()getSnapshotBeforUpdatecomponentDidUpdate()

3. Unmounting components: triggered by ReactDOM.unmountComponentAtNode()

componentWillUnmount()

Important hook

render: initialize rendering or update rendering call componentDidMount: start monitoring, send ajax request componentWillUnmount: do some finishing work, such as: clean up timer

The hook that will be abandoned

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

A warning will appear when using it now. The next major version will require the UNSAFE_ prefix to be used. It may be completely abandoned in the future and is not recommended.

This is the end of this article about the new version of react lifecycle hook function. For more relevant react lifecycle hook function content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief discussion on React Component life cycle functions
  • React State state and life cycle implementation method
  • React component life cycle example
  • React life cycle example analysis
  • React life cycle principle and usage notes
  • Comparison between Vue life cycle and react life cycle [recommended]
  • A brief discussion on the life cycle of components in React Native
  • React component life cycle detailed explanation
  • Commonplace js-react component life cycle
  • Interviewers often ask questions about React's life cycle

<<:  Tutorial on processing static resources in Tomcat

>>:  Using keras to judge SQL injection attacks (example explanation)

Recommend

Analysis of three parameters of MySQL replication problem

Table of contents 01 sql_slave_skip_counter param...

Vue ElementUI implements asynchronous loading tree

This article example shares the specific code of ...

Detailed explanation of various types of image formats such as JPG, GIF and PNG

Everyone knows that images on web pages are genera...

Basic usage and pitfalls of JavaScript array sort() method

Preface In daily code development, there are many...

Analysis of parameter transfer process of driver module in Linux

Declare the parameter name, type and permission y...

MySQL single table query example detailed explanation

1. Prepare data The following operations will be ...

Mysql anonymous login cannot create a database problem solution

Frequently asked questions Access denied for user...

MySQL free installation version configuration tutorial

This article shares the MySQL free installation c...

Solutions to Mysql index performance optimization problems

The optimization created by MySQL is to add index...

Several situations that cause MySQL to perform a full table scan

Table of contents Case 1: Case 2: Case 3: To summ...

Docker container exits after running (how to keep running)

Phenomenon Start the Docker container docker run ...

Example code of layim integrating right-click menu in JavaScript

Table of contents 1. Effect Demonstration 2. Impl...

HTML4.0 element default style arrangement

Copy code The code is as follows: html, address, ...

40 web page designs with super large fonts

Today's web designs tend to display very larg...