React Life cycle

React component life cycle

1. Component reuse

Two ways:

  • Render props model
  • High order Component (HOC)

Render – props model

The purpose of a component is to reuse data + views. One such reuse mechanism is render-props: just reuse data and pass views as they are used. Render (); render(); render(); render(); render(); – ideas:

  • The state to be reused and the methods to manipulate it are encapsulated in a component
  • When using a component, add a prop with the value of a function, obtained by the function parameter
  • Use the return value of this function as the UI content to render

Using the step

  • Create a MyMouse component that provides reusable logic code in the component
  • The state to be reused asprops.render(state)Method, exposed outside the component
  • Use the return value of props. Render () as the content to render
//index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

// Import the class component
import MyMouse from './MyMouse'
// Import images
import img from './image/5.jpg'

ReactDOM.render(<div>
    <MyMouse// Only data is transferred, images are transferred as neededrender={
            (data) = > <img src={img} style={{ position: 'absolute', top: data.y.left: data.x}} ></img>
            // (data) => <div>X :{data.x},y :{data.y}</div>} / ></div>.document.getElementById('root'));
Copy the code
//MyMouse.js
import { Component } from 'react'

export default class MyMouse extends Component {
    state = {
        x: "".y: ""
    }

    // Mouse movement triggers
    handelMouse = (e) = > {
        // console.log(e);
        this.setState({
            x: e.clientX,
            y: e.clientY
        })
    }
    // When the DOM is mounted, it is triggered
    componentDidMount() {
        window.addEventListener('mousemove'.this.handelMouse)
    }
    / / release
    componentWillUnmount() {
        window.removeEventListener('mousemove'.this.handelMouse)
    }
    render() {
        return this.props.render(this.state)
    }

}

Copy the code

Mouse following effect

Render -props for children

  • Note: Just because the mode is called Render props doesn’t have to use a prop named Render, it can actually use any prop
  • The technique for calling prop a function and telling the component what to render is called the Render props mode
  • Recommendation: Use childre instead of the Render attribute
//index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

// Import the class component
import MyMouse from './MyMouse'
ReactDOM.render(<div>
    <MyMouse>{(data) => <div>X :{data.x},y :{data.y}</div>}</MyMouse>
</div>.document.getElementById('root'));
Copy the code
//MyMouse.js
import { Component } from 'react'
// Introduce type modules
import propTypes from 'prop-types'

export default class MyMouse extends Component {
    state = {
        x: "".y: ""
    }

    // Mouse movement triggers
    handelMouse = (e) = > {
        // console.log(e);
        this.setState({
            x: e.clientX,
            y: e.clientY
        })
    }
    // When the DOM is mounted, it is triggered
    componentDidMount() {
        window.addEventListener('mousemove'.this.handelMouse)
    }
    / / release
    componentWillUnmount() {
        window.removeEventListener('mousemove'.this.handelMouse)
    }
    render() {
        return this.props.children(this.state)
    }

}
/ / check
MyMouse.propTypes = {
    children: propTypes.func.isRequired
}
Copy the code

High order Component (HOC)

The function takes a component and returns the enhanced steps to use the component

  • Create a function with a name convention beginning with
  • Specifies function arguments, which should start with an uppercase letter
  • Creates a class component inside the function that provides reusable state logic code and returns
  • In this component, the parameter component is rendered and the state is passed to the parameter component via prop
  • Call the higher-order component, pass in the component to be enhanced, get the enhanced component with the return value, and render it to the page
//index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import img from './image/5.jpg'

// 1. The function takes a component and returns the enhanced component
// The name convention begins with with
// Specify function arguments that begin with an uppercase letter
function withMouse(WrapperedComponent) {
    // 2. Create a class component inside the function that provides the reusable state logic code and returns it
    class Mouse extends Component {
        state = {
            x: "".y: ""
        }
        handelMouse = (e) = > {
            console.log(e);
            this.setState({
                x: e.clientX,
                y: e.clientY
            });
        }
        // 3. In this component, render the parameter component and pass the state to the parameter component via prop
        render() {
            return <WrapperedComponent {. this.state} / >
        }
        // When the DOM is mounted, it is triggered
        componentDidMount() {
            window.addEventListener('mousemove'.this.handelMouse)
        }
        / / release
        componentWillUnmount() {
            window.removeEventListener('mousemove'.this.handelMouse)
        }
    }
    return Mouse;
}
const Position = (props) = > <h3>X = {props. X},y = {props. Y}</h3>
const Dog = (props) = > <img src={img} style={{ position: 'absolute', top: props.y.left: props.x}} ></img>

// 4. Call the higher-order component, pass in the component to be enhanced, get the enhanced component with the return value, and render it to the page
const PositionWrapped = withMouse(Position)
const TomcatWrapped = withMouse(Dog)

ReactDOM.render(<div>
    <PositionWrapped />
    <TomcatWrapped />
</div>.document.getElementById('root'));
Copy the code

Modify the advanced component alias displayName

const PositionWrapped = withMouse(Position)
PositionWrapped.displayName = 'PositionWrapped'
Copy the code

The effect

Pass props

2. The React principle

setState()

  1. SetState is asynchronous
  2. Execute after render
  3. Multiple calls to setState will only trigger render once (solution # 5)
  4. SetState the second one has a callback to get the value of the changed state
  5. The first parameter of setState can be a function whose parameters are the state and props after the last setState change
//index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class App extends Component {
    state = {
        count: 0
    }
    handelClick = () = > {
        this.setState({
            count: this.state.count + 1
        }, function () {
            // Execute in sequence three
            console.log('within the setState:' + this.state.count);
        })
        // Execute order 1
        console.log('outside setState:' + this.state.count);
    }
    render() {
        // Execute in sequence two
        console.log('renser inside: + this.state.count);
        return (
            <div>
                <h3>{this.state.count}</h3>
                <button onClick={this.handelClick}>+</button>
            </div>
        )
    }
}
ReactDOM.render(<App />.document.getElementById('root'));
Copy the code

The way functions and objects are used

Recommended: Use setState((preState, preProps) => {}) syntax

//index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class App extends Component {
    state = {
        count: 0
    }
    handelClick = () = > {
        // the first parameter of setState can be a function, whose parameters are the state and props after the last setState change
        // The following code can be rendered superimposed
        this.setState((preState, preProps) = > {
            console.log(preState, preProps);
            return { count: preState.count + 1}})this.setState((preState, preProps) = > {
            console.log(preState, preProps);
            return { count: preState.count + 1}})this.setState((preState, preProps) = > {
            console.log(preState, preProps);
            return { count: preState.count + 1}})// The following methods only trigger once
        // this.setState({
        // count: this.state.count + 1
        // })
        // console.log(this.state.count);
        // this.setState({
        // count: this.state.count + 1
        // })
        // console.log(this.state.count);
        // this.setState({
        // count: this.state.count + 1
        // })
        // console.log(this.state.count);
    }
    render() {
        return (
            <div>
                <h3>{this.state.count}</h3>
                <button onClick={this.handelClick}>+</button>
            </div>
        )
    }
}
ReactDOM.render(<App />.document.getElementById('root'));
Copy the code