Create a way

There are two ways to create Class components

ES5 mode (obsolete)

Import React from 'React' const A = React. CreateClass ({render() {return(<div>hi</div>)}}) export default A // because ES5 does not support classesCopy the code

ES6 way

import React from 'raeact'
​
class B extends React.Component {
    constructor(props){
        super(props)
    }
    render(){
        return(
            <div>hi</div>
        )
    }
}
export default B
Copy the code

contrast

The ES6 class approach is better

If the browser does not support ES6 (IE8), use Webpack + Babel to translate ES6 to ES5

Props External data

Pass props to component B

class Parent extends React.Component { constructor(props){ super(props) this.state = {name: 'river'} } onClick = () => {} render(){ return <B name={this.state.name} onClick={this.onClick}>hi</B> } } // External data is wrapped as an object // {name: 'river', onClick:... , children: 'hi'} // Here onClick is a callbackCopy the code

Initialize the

class B extends React.Component {
    constructor(props){
        super(props);
    }
    render(){}
}
Copy the code

Either no initialization, i.e., no constructor

Either initialize and write the whole thing

Effect: After doing this, this.props is the address of the external data object

Read the props

class B extends React.Component { constructor(props) { super(props); } render(){ return <div onClick={this.props.onClick}> {this.props.name} <div> {this.props.children} </div> </div> } } // Read from this.props. XXXCopy the code

Write props

Change the value of props (an address)

This.props = {/* Another object */}

Note: code written this way makes no sense, since it is external data, it should be updated externally

Change the properties of props

this.props.xxx='hi'

Note: code written this way makes no sense, since it is external data, it should be updated externally

The principle of

Changes should be made to the data by its owner

The hook

ComponentWillReceiveProps hooks

This hook is emitted when a component accepts new props

Hooks are “special functions”

The sample

The hook is deprecated

Renamed UNSAFE_componentWillReceiveProps

The role of Props

Accept external data

Read but not write. External data is passed by the parent component

Accept external functions

This function is called at the appropriate time, and is typically a function of the parent component

State & setState

Initialize the State

class B extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      user: {name: 'river', age: 18}
    }
  }
  render() {/* ... */}
}
Copy the code

The State of reading and writing

Read in this state

this.state.xxx.yyy.zzz
Copy the code

Written by enclosing setState (????? ,fn)

The sample

This.setstate (newState,fn) // Note that setState will not change this.state immediately, but will update this.state after the current code is finished, thus triggering a UI updateCopy the code
This.setstate ((state,props)=> newState,fnCopy the code

Shallow merge when written

SetState automatically merges the new state with the old state

Modify the this.state property value directly

this.state n += 1
this.setState(this.state)
Copy the code

It can be implemented, but is not recommended

Lifecycle

The life cycle

Like the following code

Let div = document.createElement('div') // This is the create/construct procedure for div. TextContent = 'hi' // this is the initialization state Document. The body. The appendChild (div)/div. / this is div mount process textContent = 'hi2' / / this is the update process of div div. Remove () / / this is a div Unmount to processCopy the code

In the same way

The React component also has these processes, which we call the life cycle

Function list

  • constructor()Initialize state here
  • static getDerivedStateFromProps()
  • shouldComponentUpdate()Return true/false Updates/blocks updates
  • render()Creating a virtual DOM
  • getSnapshotBeforeUpdate()
  • componentDidMount()The component appears on the page
  • componentDidUpdate()Component updated
  • componentDidUnmount()Components will die
  • static getDerivedStateFromError()
  • componentDidCatch()

constructor

USES:

  • Initialize the props

  • Initialize state, but setState cannot be called at this time

  • It’s called bind this

    Constructor (){// this.onclick = this.onclick.bind (this)} // Use the new syntax instead of onClick = () => {} constructor(){ /* * *}Copy the code
  • Don’t write

shouldComponentUpdate

USES:

  • Returning true does not block UI updates

  • Returning false prevents UI updates

  • The sample

    Take some inspiration from the example above — compare each property of newState to this.state. If they’re all equal, they don’t update, if they’re all unequal, they update.

    React actually has this functionality built in, for example

    The React.PureComponent compares each key of the new state to the old state and each key of the new props to the old props before render.

    If all keys have the same value, no render is performed; Render if any key value is different.

    Note that this comparison is only one layer.

render

USES:

  • Show the view

    return (<div>... </div>)

  • There can only be one root element

  • If there are two root elements, use the < react. Fragment> content
    , which can be shortened <>

The sample

Use < react. Fragment/> or <>, which acts as a placeholder and will not be displayed after rendering

If div> is wrapped around it, the div layer is always displayed

Skills:

The sample

  • Render can do thatif... else
  • Render can do that? :expression
  • Render can do that&&and||expression
  • Can’t write directly in renderforFor a loop, you need an array
  • Render can do thatarray.map(cycle)

componentDidMount()

USES:

  • The code executed after the element is inserted into the page relies on the DOM

    For example, to get the width of a div, it’s best to write it here

  • Here you can make AJAX requests to load data (official recommendation)

  • The first rendering executes this hook

The sample

About the Ref used in the above code

componentDidUpdate()

USES:

  • Execute code after view update
  • It can also be initiated hereAJAXRequest, forUpdate data (see documentation)
  • The first rendering does not execute this hook
  • Here,setStateMay cause an infinite loop unless placed inifIn the
  • ifshouldComponentUpdatereturnfalse, the hook is not triggered

Parameters:

componentDidUpdate(prevProps, prevState, snapshot)
Copy the code

componentWillUnmount

USES:

  • The code is executed when the component is about to be removed from the page and destroyed
  • unmountComponents that pass will not be againmount

For example:

If the c.. DidMount is listening for window.scroll, so c.. Cancel listening in WillUnmount

If the c.. DidMount created Timer, so it’s in c.. Cancel Timer in WillUnmount

If the c.. DidMount creates AJAX requests in c.. Cancel request inside WillUnmount

Look at the sequence of hook execution in stages