Start from zero react = > react component advanced

Keywords: React

props verification - basic usage:

In the previous blog, we mentioned the verification of props, as shown in the figure:

  Props verification: for child components, props is foreign (it accepts the parameters passed by the parent component), and it is impossible to guarantee the format of data passed in by the component user. With type verification, our program will be more robust.

Basic usage of props:

  1. Import the prop types package. This package comes with the scaffold when the project is created, and no additional installation is required
  2. Use the component name. propTypes = {property name 1: type 1,...} to add verification rules (fixed writing) to the props of the component

As shown in the figure:

  effect:   Specify that the type of props you receive must be a type you receive. If it is not an array, an error will be reported, which makes us use it more clearly. (the error is shown in the figure)

props verification - common rules:

1 - common types: array, bool, func, number, object, string

2-React element type: element

3 - required item: isRequired

4 - structure specific objects: shape({})

Listed Code:

Com.propTypes = {
  fn: PropTypes.func, // fn is the function type
  isEdit: PropTypes:bool.isRequired // The type of isEdit is bool and must be passed in
  
  // Structure specific objects
  goodInfo: PropTypes.shape({ // The format of goodInfo is an object with numeric price attribute and string name attribute
    price: PropTypes.number,
    name: PropTypes.string
  })
}

props default (understand):

Default value: we need to know what is the default value. The original meaning is a value that will be contained in itself. We know that props is passed from the parent component, so the default value of props is to assign a value to the attribute without assignment

Method:

  1. defaultProps
  2. Default value of deconstruction assignment

Specific use:

// Defaultprops (the component does not pass the pageSize property)
class App extends React.Component{
    return (
        <div>
            Show here props Default values for:{ this.props.pageSize }
        </div>
    )
}
// Set defaults
App.defaultProps = {
	pageSize: 10
}
// Type restrictions
App.propTypes = {
  pageSize: PropTypes.number
}



// deconstruction
class App extends React.Component{
    return (
     // Default value of deconstruction assignment
     const { pageSize = 10} = this.props
        <div>
            Show here props Default values for:{ this.props.pageSize }
        </div>
    )
}
// Type restrictions
App.propTypes = {
  pageSize: PropTypes.number
}

  Note: after the parent component passes the props value, the passed value will prevail and the default value will not be used

For more details, see:   Static type verification in React - PropTypes learning_ Suwu150 CSDN blog

Component lifecycle:

When we learn vue, we understand the concept of life cycle, which is the whole process of things from creation to final extinction, and the life cycle of components: the process of components from being created, mounted to running in the page, and then unloaded when components are not in use. There will be different functions automatically called and executed at different stages of the life cycle, which is also called hook functions (only class components have lifecycle hook functions)

Here is a picture:

  From the above figure, we can see that there are three stages and five hook functions in the class component

Mount phase

It can be seen from the figure above that the hook functions are executed in the order of constructor() - > render() - > componentdidmount(),

When the component is executed, it is simply when the page is loaded

Actual:

 

  After knowing the execution sequence of the hook function in the mount phase, what is the trigger time of the hook function in the mount phase and what is its function?

 

 

Update phase

As shown in the big picture above, we can also see that two hooks will be executed in the update phase: render() > componentdidupdate()

  As the name suggests, update means that when the data changes and a new props is received, or this.setState is called, or forceUpdate() is called, the component will enter the update phase

What can be done in the update phase:

Unloading phase

  Cleaning timer list code:

/* eslint-disable react/prop-types */
import React, { Component, createRef } from 'react'
import ReactDOM from 'react-dom'

class Son extends Component {
  constructor () {
    super()

    this.timer = setInterval(() => {
      console.log('Subcomponents:', Date.now())
    }, 1000)
  }

  render () {
    return <div>Subcomponents:{this.props.content}</div>
  }

  componentDidUpdate () {
    console.log('Subcomponents: componentDidUpdate')
  }

  componentWillUnmount () {
    console.log('Subcomponent uninstall: componentWillUnmount')
    // Delete timer
    clearInterval(this.timer)
  }
}

export default class App extends Component {
  constructor () {
    super()
    console.log('1. constructor')
    this.state = {
      content: '',
      isShow: true
    }
    this.refTxt = createRef()
  }

  hChange = (e) => {
    this.setState({ content: e.target.value })
  }

  click = () => {
    this.forceUpdate()
  }

  render () {
    console.log('2. render')
    return (
      <div>
        <button onClick={this.click}>to update</button>
        assembly<input value={this.state.content} onChange={this.hChange} />
        <br />
        {this.state.isShow && <Son content={this.state.content} />}
      </div>
    )
  }

  componentDidMount () {
    console.log('3. componentDidMount')
    console.log(this.refTxt.current)

    // axios.get()
  }

  componentDidUpdate () {
    console.log('Update complete: componentDidUpdate')
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

1 -- timer with timing printing time in sub assembly  

  2 - destroy sub assemblies

 

  3 - execute the clear timer in the hook function during the unloading phase

 

  For more information about life cycle, please see this detailed analysis: Detailed explanation of React component life cycle glowing firefly CSDN blog

 

 

Posted by alkhatareykha on Wed, 10 Nov 2021 17:17:24 -0800