React component communication and lifecycle

1. Component communication method

1.1 Basic Usage

  • Because components are “independent,” the concepts of in-component and out-component arise

  • A component passes data from outside to inside through the component property < component name property ={} />

  • To receive data within a component, use props to receive data passed in (function components and class components)

  • The function component uses the data passed through the props parameter, and the class component uses the data passed through the this.props parameter

    Use component to pass values

    <Hello name="Jack" age={19} />
    Copy the code

    Function components use data passed in

    function Hello(props) {
        console.log(props)
        return (
            <div>{props.name}</div>)}Copy the code

    Class components use the data passed in

    class Hello extends React.Component {
        render() {
            return (
                <div>{this.props.age}</div>)}}Copy the code

1.2 the characteristics of

  • You can pass any type of data to a component

  • Props is a read-only object that can only read the value of the property and cannot modify the object

  • Note: When using class components, if you write a constructor, you should pass props to super(), otherwise you cannot get this.props in the constructor

    class Hello extends React.Component {  
        constructor(props) {
            // It is recommended to pass props to the parent constructor
            super(props)
        }
        render() {
            return <div>{this.props.age}</div>}}Copy the code

2. Three modes of component communication

  • The father the son
  • Child the parent
  • Non-parent component

2.1 Parent component passes data to child component

  • The parent component determines the data to be passed to the child component, usually stored in state

  • Add attributes to child component tags with values of data in state

  • The child component receives data passed in the parent component through props

    The parent component

    class Parent extends React.Component {
        state = { lastName: 'the king' }  
        render() {
            return (
                <div>Passing data to child components:<Child name={this.state.lastName} />
                </div>)}}Copy the code

    Child components

    function Child(props) {
        return <div>Data received by the child component: {props. LastName}</div>
    }
    Copy the code

2.2 Child component passes data to parent component

With the callback function, the parent component provides the callback, the child component calls, and the data to be passed as arguments to the callback function

  • The parent component defines a callback function (to receive data)

  • The parent component passes the callback function to the child component as the value of the property

  • The child component gets the callback function through props and calls it. The arguments to the callback function are passed back to the parent component as data

    The parent component

    class Parent extends React.Component {
        // The function passed to the child component
        getChildMsg = (msg) = > {
            console.log('Subcomponent data received', msg)
        }
        render() {
            return (
                <div>Child components:<Child sendMsg={this.getChildMsg} />
                </div>)}}Copy the code

    Child components

    class Child extends React.Component {
        state = { childMsg: 'React '} handleClick = () => {this.props. SendMsg (this.state.childmsg)} render() {return (
            )>Copy the code

2.3 Non-parent and child Components

  • Promote the shared state to the nearest public parent, which manages the state
  • State of ascension
  • The common parent component is responsible for: 1. Providing shared state 2. Providing methods to manipulate shared state
  • A child component to communicate simply needs methods to receive state or operation state through props

3. Context

Non-parent component values need to be indirectly passed by the common parent component, which is cumbersome. The recommended way to pass data across components is to use Context

Using the step

  1. Call React. CreateContext () to create the Provider and Comsumer components

    const { Provider, Comsumer } = React.createContext()
    Copy the code
  2. Use the Provider component as the parent node

    <Provider>
        <div className="App">
            <Child />
        </div>
    </Provider>
    Copy the code
  3. Sets the value property to represent the data to be passed

    <Provider value="pink">
        <div className="App">
            <Child />
        </div>
    </Provider>
    Copy the code
  4. Call the Comsumer component to receive the data

    <Comsumer> {data => <h1> Received data: {data}</h1>}</ Comsumer>Copy the code

conclusion

  1. Context can be used to communicate components if they are nested in multiple layers in the next year
  2. Context provides two components: Provider and Comsumer
  3. Provider component: Used to provide data
  4. Comsumer component: Used to consume data

4. The props

4.1 children attribute

  • Children property: Represents the children of the component label. Props has this property when the component tag has child nodes

  • The children attribute, like ordinary props, can have any value

    function Hello(props) {
        return (
            <div>Children of the component: {props. Children}</div>)}// I am a child node<Hello> I am a child node </Hello>Copy the code

4.2 props check

  • For a component, props is a container for external data. There is no guarantee of what format the component consumer will pass in

  • If the data is passed in the wrong format, an error may occur within the component

  • Key: No additional error message except syntax error message

    // Create the component
    function App(props) {
        const arr = props.colors
        const list = arr.map((item, index) = > <li key={index}>{item}</li>)
        return (
            <ul>{list}</ul>)}// When using components
    <App colors={19} / >Copy the code
  • Props verification: Allows you to specify the type, format, and so on of props when creating a component

  • Function: Captures errors caused by props when using components, and provides clear error messages to enhance the robustness of components

    App.propTypes = {
        colors: PropTypes.array
    }
    Copy the code

Using the step

  1. Install prop-types NPM I prop-types

  2. Import prop – types package

  3. PropTypes = {} to add validation rules to the props of the component

  4. Validation rules are specified using the PropTypes object

    import PropTypes from 'prop-types'  
    function App(props) {
        return (
            <h1>Hi, {props.colors}</h1>
        )
    }
    
    App.propTypes = {
        // The convention colors attribute is array
        // If the type is incorrect, an explicit error is reported to facilitate analysis of the cause of the error
        colors: PropTypes.array
    }
    Copy the code

Constraint rules

  1. Common types: Number, String, array, bool, func, and Object

  2. React Element type: Element

  3. Mandatory: isRequired

  4. Object of specific structure: Shape ({})

    // Common types
    optionalFunc: PropTypes.func,
    / / will be selected
    requiredFunc: PropTypes.func.isRequired,
    // Objects of a specific structure
    optionalObjectWithShape: PropTypes.shape({
        color: PropTypes.string,
        fontSize: PropTypes.number
    })
    Copy the code

Default value of 4.3 props

  • Scenario: Paging component –> Number of entries per page

  • Function: Set the default value for props, which takes effect when no props is passed

    function App(props) {
        return (
            <div>Here is the default value for props: {props. PageSize}</div>)}// Set the default value
    App.defaultProps = {
        pageSize: 10
    }
    // No pageSize attribute is passed in
    <App />
    Copy the code

5. Component lifecycle

5.1 Component Lifecycle Overview

  • Component life cycle: The process of creating a component, mounting it to the page (display), and uninstalling it from the page (disappear)
  • Each phase of the lifecycle is always accompanied by method calls that are the hook functions of the lifecycle.
  • Hook functions provide opportunities for developers to manipulate components at different stages.
  • To understand the life cycle of a component is to understand how it works, which can help us to implement more complex components and analyze the causes of component errors
  • Only class components have a life cycle.

5.2 Three phases of the life cycle

5.2.1 Creation Phase (Mounting)

  1. Execution time

    When a component instance is created and inserted into the DOM

  2. Execution order

    constructor() —> render() —> componentDidMount()

  3. role

    Hook function trigger role
    constructor When a component is created, it is executed first 1. Initialize state 2. Bind this to the event handler
    render Emitted each time the component state changes Render UI (note that setState() cannot be called)
    componentDidMount After the component is mounted 1. Send a network request. 2

5.2.2 Update Phase

  1. Execution time

    1. SetSate () 2.forceUpdate () 3. The component receives new props (any of the above occurs, triggering the component to re-render)
  2. Execution order

    render() —> componentDidUpdate()

  3. role

    Hook function trigger role
    render Fires every time a component is rendered To render the UI
    componentDidUpdate After the component is updated (DOM rendering complete) Note: setState() must be placed in an if condition

5.2.3 Unloading stage

  1. Execution time

    The component disappears from the page

  2. Execution order

    componentWillUnmount()

  3. role

    Hook function trigger role
    componentWillUnmount Component unmount (disappear from page) Perform cleanup (e.g., cleanup timer, event unbinding, etc.)