1 Create the Class component

  • ES5 mode (obsolete)

    import React from 'react'
    
    const A = React.createClass({
    	render(){
    		return(
    			<div>hi</div>)}})export default A
    Copy the code
  • ES6 way

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

2 Props External data

  • Pass props to component B

    import React from 'react'
    
    class Parent extends React.Component {
      // Initialize this. Props to be the address of the external data object
    	constructor(props){
    		super(props);
        // State of the parent element as props
        this.state = {name : 'frank'}
    	}
      onClick = () = > {}
    	render() {
    		return({/* use this.state.name as the external data for B */}
    			<	B name = {this.state.name}
            {/* Pass the external onClick function to B onClick, where onClick is a callback */}
            	onClick = {this.onClick}>hi</B>
    		)
    	}
    }
    // {name: 'frank', onClick: ... , children: 'hi'}
    export default B
    Copy the code
  • 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. XXX
    Copy the code
  • Write props

    In principle, changes to data should be made by the owner of the data

  • The role of props

    • Accept external data

      You can only read but not write

      External data is passed by the parent component

    • Accept external functions

      Call this function when appropriate

      This function is typically a function of the parent component

3 State Internal data

  • Initialize the State

    class B extends React.Component{
    	constructor(props){
    		super(props);
    		this.state = {
    			user: {name : 'frank'.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)

      1. this.setState(newState, fn)

        Note that setState does not change this.state immediately. It will update this.state after the current code runs, triggering a UI update

      2. this.setState((state,props) => newState,fn)

        Understandably, fn executes after a successful write

      onClick = () => {
          this.setState({
              x: this.state.x + 1
          })
      }
      
      onClick2 = () => {
          this.setState((state) => ({x: state.x + 1}))
      }
      Copy the code

4 Life Cycle

  • Like the following code

    let div = document.createElement('div')
    // This is the div create/construct process
    div.textContent = 'hi'
    // This is the initialization state
    document.body.apppendChild(div)
    // This is the div mount process
    div.textContent = 'hi2'
    // This is the div update process
    div.remove()
    // This is div's numount procedure
    Copy the code
  • List of lifecycle functions

    Constructor () – Initialize state here

    static getDerivedStateFroProps()

    ShouldComponentUpdate () – return false to block updates

    Render () – Creates the virtual DOM

    getSnapshotBeforeUpdate()

    ComponentDidMount () – The component already appears on the page

    ComponentDidUpdate () – The component is updated

    ComponentWillUnmount () – Components will die

    static getDerivedStateFromError()

    componetDidCatch()

4.1 the constructor

  • use

    • 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)}Copy the code

      New syntax

      onClick = () = > {}
      constructor(){... }Copy the code
  • Don’t write

4.2 shouldComponentUpdate

  • use

    Returning true does not block UI updates

    Returning false prevents UI updates

  • The interview often ask

    • shouldComponentUpdate
    • A: It allows us to manually determine whether component updates are needed, and we have the flexibility to set the return value based on the application scenario to avoid unnecessary updates
  • The sample

    import React from 'react'
    
    class App extends React.PureComponent {
    // 1. Initialize
        constructor(props) {
            super(props)
            // 2. Set variables
            this.state = {
                n: 1}}// 3. Make n+1 and -1, the UI does not change, but every time you click the button render once
        onClick = () = >{
            this.setState(state= > ({
                n: state.n + 1
            }))
            this.setState(state= > ({
                n: state.n - 1
            }))
            {n:1} and {n:1} are different objects, but have the same value
        }
        // Compare the old n with the new n
        // shouldComponentUpdate(nextProps, nextState) {
        // return nextState.n ! == this.state.n;
            // Return true does not block UI updates
            // Return false to prevent UI updates
        // }
    
        render() {
            console.log('Render once')
            return(
                <div>App
                    <div>
                        {this.state.n}
                        <button onClick={
                            this.onClick} >+ 1</button>
                    </div>
                </div>)}}export default App;
    Copy the code

  • You can replace this hook with a PureComponent

    class App extends React.PureComponent{}
    Copy the code
    • The 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.

4.3 render

  • use

    Display view, return (

    )

    There can only be one root element. If there are two root elements, they must be wrapped in < react. Fragment>.

  • skills

    • Render can say if. Else
    • Render can say, okay? Expression:
    • Render cannot write for loop directly in render, need to use array
    • Render: Array map(loop)
render() {
        return (
            <>
                {this.state.n % 2 === 0 ?
                    <div>An even number</div> : <span>An odd number</span>
                }
                <button onClick={this.onClick}>+ 1</button>
            </>)}Copy the code

4.4 componentDidMount

The component is already mounted

  • use
    • Execute code after the element is inserted into the page. This code relies on the DOM, and if you want to get the height of a div, for example, write it here
    • Here you can make AJAX requests to load data (official recommendation)
    • The first render executes the secondary hook
  • The sample
import React from 'react'

class App extends React.PureComponent {
    divRef = undefined

    constructor(props) {
        super(props)

        this.state = {
            n: 1.width: undefined
        }
        this.divRef = React.createRef()
    }


    componentDidMount() {
        const div = this.divRef.current
        const {width} = div.getBoundingClientRect()
        this.setState({width})
    }

    render() {
        return (
            <div ref={this.divRef}>Hello, {this. State. Width} px</div>)}}export default App;

Copy the code

4.5 componentDidUpdate

  • use
    • Execute code after view update
    • AJAX requests can also be made here to update the data
  • Pay attention to
    • The first rendering does not execute this hook
    • Here setState may cause an infinite loop, except in if
    • ifshouldComponentUpdateIf false is returned, this hook is not fired

4.6 componentWillUnmount

  • use

    The code is executed when the component is about to be removed from the page and destroyed

    Components that have been unmounted will not be mounted again

  • For example,

    • If you’re listening for Window Scroll in componentDidMount, you need to unlisten for componentWillUnmount

    • If an AJAX request is created in componentDidMount, cancel the request in componentWillUnmount

4.7 Life Cycle Summary