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

JavaScript Basics Variables

Table of contents 1. Variable Overview 1.1 Storag...

Let's talk about the LIMIT statement in MySQL in detail

Table of contents question Server layer and stora...

Nofollow makes the links in comments and messages really work

Comments and messages were originally a great way...

25 Tools to Improve Website Usability and Conversion Rates

For a website, usability refers to whether users c...

CentOS 7.5 deploys Varnish cache server function

1. Introduction to Varnish Varnish is a high-perf...

Vue/react single page application back without refresh solution

Table of contents introduction Why bother? Commun...

Vue realizes the sliding cross effect of the ball

This article example shares the specific code of ...

Example code for implementing a pure CSS pop-up menu using transform

Preface When making a top menu, you will be requi...

How to create WeChat games with CocosCreator

Table of contents 1. Download WeChat developer to...

HTML table tag tutorial (24): horizontal alignment attribute of the row ALIGN

In the horizontal direction, you can set the row ...

Detailed explanation of Apache website service configuration based on Linux

As an open source software, Apache is one of the ...