New version of react life cycle hook function and usage details

Time:2022-6-11

Compared with the old life cycle

在这里插入图片描述

Three hooks are ready to be discarded. Two hooks have been added

After react16, three lifecycles are discarded (but not deleted)

  • Componentwillmount (hook on which the component will be mounted)
  • Componentwillreceiveprops (hook when the component is about to receive a new parameter)
  • Componentwillupdate (hook to be updated by the component)

New hooks in the life cycle of the new version

  •  getDerivedStateFromProps
  • New attributes and status can be obtained through parameters
  • The function is static
  • The return value of this function will overwrite the component status

getSnapshotBeforeUpdate

  1. The real DOM build is complete, but it has not actually been rendered into 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 you need to give a return value


The return value can be either state obj or null
If the return value is state obj, the previous value will be overwritten and cannot be changed
Returning null has 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 both in person and time, you can use getderivedstatefromprops

在这里插入图片描述

<div></div>
  <!--  Introducing react core library -- >
  <script src="../js/17.0.1/react.development.js"></script>
  <!--  Introduce react DOM to support react DOM -- >
  <script src="../js/17.0.1/react-dom.development.js"></script>
  <!--  Introducing 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)
      //Initialization status
      this.state = {count:0}
    }

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

    //Callback for unload component button
    death=()=>{
      ReactDOM.unmountComponentAtNode(document.getElementById('test'))
    }

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

    //Force callback of update button
    force=()=>{
      this.forceUpdate()
    }

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

    //Valve for control assembly renewal
    shouldComponentUpdate(){
      console.log('Count---shouldComponentUpdate')
      //If the return value is false, the default value is true when the valve is closed
      return true
    }

    //Hook after component update
    componentDidUpdate(){
      console.log('Count---componentDidUpdate')
    }

     //Hook that the component will unload
     componentWillUnmount(){
      console.log('Count---componentWillUnmount');
    }

    render(){
      console.log('Count---render')
      const {count} = this.state
      return(
        <div>
          <h2>The current sum is: {count}</h2>
          <button onclick={this.add}> click me +1</button>  
          <button onclick={this.death}> click I uninstall components </button>  
          <button onclick={this.force}> click I force update (do not change data) </button>  
        </div>
      )
    }
  }
  
  //Render components
    ReactDOM.render(<Count count={166}/>,document.getElementById('test'))
  </script>

results of enforcement

在这里插入图片描述

getSnapshotBeforeUpdate

The return value can be null or a snapshot
If it is null, it has no effect
If it is a snapshot, you can pass the return value to the third parameter of componentdidupdate
Three parameters that componentdidupdate can receive
namely
Snapshots returned by previous props, previous state, and getsnapshotbeforeupdate
prevprops、 prevstate、snapshotValue

在这里插入图片描述

<div></div>
  <!--  Introducing react core library -- >
  <script src="../js/17.0.1/react.development.js"></script>
  <!--  Introduce react DOM to support react DOM -- >
  <script src="../js/17.0.1/react-dom.development.js"></script>
  <!--  Introducing 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)
      //Initialization status
      this.state = {count:0}
    }

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

    //Callback for unload component button
    death=()=>{
      ReactDOM.unmountComponentAtNode(document.getElementById('test'))
    }

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

    //Force callback of update button
    force=()=>{
      this.forceUpdate()
    }

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

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

    //Valve for control assembly renewal
    shouldComponentUpdate(){
      console.log('Count---shouldComponentUpdate')
      //If the return value is false, the default value is true when the valve is closed
      return true
    }

    //Hook after component update
    componentDidUpdate(preProps,preState,snapshotValue){
      console.log('Count---1componentDidUpdate',preProps,preState,snapshotValue);
    }

     //Hook that the component will unload
     componentWillUnmount(){
      console.log('Count---componentWillUnmount');
    }

    render(){
      console.log('Count---render')
      const {count} = this.state
      return(
        <div>
          <h2>The current sum is: {count}</h2>
          <button onclick={this.add}> click me +1</button>  
          <button onclick={this.death}> click I uninstall components </button>  
          <button onclick={this.force}> click I force update (do not change data) </button>  
        </div>
      )
    }
  }
  
  //Render components
    ReactDOM.render(<Count count={166}/>,document.getElementById('test'))
  </script>

summary

Three phases of the life cycle (New)

1、 Initialization phase: by reactdom Render() trigger – first render

constructor()getDerivedStateFromPropsrender()componentDidMount()

2、 Update phase: this Setsate() or parent component re render trigger

getDerivedStateFromPropsshouldComponentUpdate()render()getSnapshotBeforeUpdatecomponentDidUpdate()

3、 Uninstall component: by reactdom Unmountcomponentatnode() trigger

componentWillUnmount()

Important hook

Render: initialize rendering or update rendering call componentdidmount: enable listening and send Ajax request componentwillunmount: do some finishing work, such as clearing the timer

Hook to be discarded

  1.  componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

A warning will appear when you use it now. Unsafe needs to be added to the next large version_ Prefixes can only be used. They may be completely discarded in the future and are not recommended.

This is the end of this article about the new version of react life cycle hook function. For more information about react life cycle hook function, please search the previous articles of developeppaer or continue to browse the following articles. I hope you will support developeppaer in the future!

Recommended Today

A front-end developer's Vim is the same as an IDE

Here is my new configurationjaywcjlove/vim-webI've been grinding it, and it's basically ready to use. Take it out and cheat the star Install The latest version of Vim 7.4+ uses (brew install macvim) installation, vim version updatebrew install macvim –override-system-vim View configuration locations # Enter vim and enter the following characters :echo $MYVIMRC download vim-web Download […]