React Component communication development outline

  • Recognize componentization
    • The idea of componentization
    • What is componentized development?
    • React componentization
    • React Component Classification
  • React create component
    • Class components
    • The return value of the Render function
    • Function component
  • React lifecycle
    • Know the life cycle
    • Life cycle analysis
    • Application scenarios of life cycle functions
    • Life cycle functions not commonly used
  • Nesting of the React component
    • Recognize nesting of components
    • Understand communication between components
  • Communicate between the React and parent components
    • Parent passes child components -props
    • Property validation -propTypes
    • Child component pass Parent component – function pass
  • React Communicates with non-parent and child components
    • The Context is introduced
    • The Context used
    • Component communication diagram
  • React Communication Supplement
    • React slot
    • Properties on
  • Events Event bus
    • events
  • refs
    • How to use ref
    • The type of the ref
  • Controlled components and uncontrolled components
    • Understanding controlled components
    • Basic walkthrough of controlled components
    • Additional walkthroughs of controlled components
    • Uncontrolled components (Understanding)
  • High order component
    • Recognize higher-order functions
    • Definition of higher-order components
    • Advanced component application scenarios
    • Meaning of higher-order components
    • Forward of ref (get functional component DOM)
  • Portals
    • The use of the Portals
  • Fragment
    • The use of fragments
  • StrictMode
    • StrictMode is introduced
    • What does strict mode check for?
  • Summary of componentized development mind map

Recognize componentization

1. Componentization idea

  • When people deal with complex problems:
    • Take complex “problems apart” and break them into manageable pieces
    • When you “put it all together,” you’ll find that the big problems will be solved

  • In fact, the above idea is the idea of divide and rule:
    • Divide and conquer is an important idea of software engineering and the cornerstone of complex system development and maintenance
    • The current modular and componentization of the front end is based on the idea of divide and conquer

2. What is componentized development?

  • Componentization is a similar idea:
    • If we put all the logic in a page together, it will become very complicated to deal with, which is not conducive to subsequent management and expansion
    • But if we “break up a page into small functional blocks”, each feature “does its own independent function”, then the management and maintenance of the entire page is very easy
React component development
  • We need to think of the entire application in terms of componentization:
    • We split a complete page into many components
    • Each component is used to implement a functional block of the page

3.React componentization

  • Componentization is the core idea of React. The App encapsulated above is itself a component
    • Componentization provides an abstraction that allows us to develop individual reusable components to construct our applications
    • Any application is abstracted into a tree of components

  • Application of componentization:
    • As much as possible, break the page up into small, reusable components
    • This makes our code easier to organize and manage, and also more extensible

4.React component classification

  • The React of componentsRelative to the VueMore flexibility and variety, can be divided into many classes of components in different ways:
    • Components can be divided into “Functional Component” and “Class Component” depending on how they are defined.
    • Components can be divided into Stateless Component and Stateful Component according to whether there is a Stateful Component to maintain.
    • Components can be divided into Presentational components and Container Components, depending on their responsibilities.
  • There is a lot of overlap between these concepts, but they are primarily concernedData logicandThe UI displayThe separation of:
    • Functional components, stateless components, and presentation components focus on “UI presentation”
    • Class components, stateful components, container components focus on “data logic”

React lifecycle

1. Recognize the life cycle

Many things have a whole process from creation to destruction. This process is called the life cycle

The React component also has its own life cycle, and understanding the life cycle of the component allows you to do what you want in the most appropriate place

  • Life cycle is an abstract concept. The whole process of life cycle is divided into many stages:

    • Such as the loading phase (Mount), the process by which the component is first rendered in the DOM tree
    • For example, the update phase (Update), the component state changes, and the rendering process is updated
    • For example, the unloading process (Unmount), the process by which a component is removed from the DOM tree
  • React calls back to predefined functions implemented within components to tell us what phase we are in. These functions are called lifecycle functions

    • Such as the implementationcomponentDidMountFunction: The component is called back when it is already mounted to the DOM
    • Such as the implementationcomponentDidUpdateFunction: The component is called back when it has been updated
    • Such as the implementationcomponentWillUnmountFunction: Callback occurs before component is unloaded and destroyed
  • When we talk about the React lifecycle, we mainly talk about the class lifecycle, because functional components have no lifecycle functions

    • (We can emulate some lifecycle callbacks later using hooks)

2. Life cycle analysis

  • Let’s start with the most basic and commonly used lifecycle functions:

3. Application scenarios of life cycle functions

Constructor

  • If not initializedstateOr method binding is not requiredReactComponent implementation constructor
  • constructor It usually does two things:
    • By givingthis.stateAssign object toInitialize the internal state
    • Bind this to the event

componentDidMount

  • componentDidMount()Will be inAfter the component is mounted(inserted into the DOM tree) immediately called
  • componentDidMount()What operations are usually performed in?
    • Dom-dependent operations can be performed here
    • This is the best place to send a network request (official advice)
    • You can add some subscriptions here (unsubscribe at componentWillUnmount)

componentDidUpdate

  • componentDidUpdate()Will be inIt will be invoked immediately after the updateThe first render will not be executed
    • When the component is updated, you can manipulate the DOM
    • If you compare the props before and after the update, you can also make a network request here (for example, the network request will not be executed if the props are not changed)

componentWillUnmount

  • componentWillUnmountWill be in the componentCalled before uninstall and destroy
    • Perform the necessary cleanup operations in this method
    • For example, clear timers, cancel network requests, or clear subscriptions created in componentDidMount()

3. Uncommon lifecycle functions

In addition to the lifecycle functions described above, there are some lifecycle functions that are not commonly used

  • getDerivedStateFromProps
    • stateThe value of is dependent at any time onpropsThe use of
    • This method returns an object to update state
  • getSnapshotBeforeUpdate
    • A function called back before React updates the DOM
    • You can get some information about the DOM before it is updated (for example, scroll position)

  • For more information on the life cycle, please refer to the official website


Nesting of the React component

1. Understand the nesting of components

  • Nested relationships exist between components:
    • In the previous case, we just created a component App
    • If an application puts all of its logic into one component, that component becomes bloated and difficult to maintain
    • So the core idea of componentization should be to break up components into smaller components
    • These components are assembled and nested together to form our application

  • The nesting logic above is as follows
    • The App component is the parent of the Header, Main, and Footer components
    • Main is the parent of the Banner and ProductList components

2. Understand the communication between components

  • During development, we often encounter needsComponents communicate with each other
    • Such asApp More than one may be usedHeaderComponents, everywhereHeaderThe content presented is different, so we need the user to pass toHeaderSome data, and let it go on display
    • Or we’re inMainComponent requested onceBannerData andProductList Data, then you need to pass it to them for presentation
  • Anyway, in aReact Communication between components is very important in a project


Communicate between the React and parent components

1. Parent passes child components -props

The parent component is presenting the child component and may pass some data to the child component

  • The parent component passes data to the child component in the form of property = value
  • The child component gets the data passed by the parent through the props parameter

The function component passes Props


2. Property validation -propTypes

  • For data passed to child components, sometimes we might want toType verification of dataEspecially for large projects
    • Of course, if you inherit by default in your projectFloworTypeScript, then you can do type validation directly
    • But even if we don’t use itFloworTypeScript, can also passprop-type Library for parameter verification
  • usepropTypes To carry out thepropsValidation, first: importprop-types
  • This is the default value of the props checksum.For more information, please refer to the official website)
    • Such as aThe props property must be passedThe use of:propTypes.string.isRequired
  • If it’s not passed onpropsWe hope soThe default valueUse:Class name. DefaultProps = {}
// 1. Import prop-types to verify properties
import propTypes from 'prop-types'

// 2. Type verification: use prop-types to verify that the props passed by the parent conform to the expected props types
Static propTypes = {static propTypes = {static propTypes = {
ChildCpn.propTypes = {
  // The name attribute is mandatory
  name: propTypes.string.isRequired,
  age: propTypes.number,
  height: propTypes.number,
}

// 3. Default value, which is the default value when the parent component does not pass props
ChildCpn.defaultProps = {
  name: 'hali'.age: 21.height: 1.77,}Copy the code

3. Child component pass Parent – function pass

  • When a child component needs to pass a message to its parent:
    • invueIs done through custom events
    • inReactIn also passedpropsThe message
    • Just let theThe parent component passes a callback to the child component, which is called in the child component
      • Pay attention tothisThe binding problem
/ / the parent component
render() {
  return (
    <div>
      <h2>Current count: {this.state.counter}</h2>The parent component passes a callback function, and the child component calls the method */ /}<Counter increment={e= > this.increment()} />
    </div>)}increment() {
  this.setState({
    counter: this.state.counter + 1})},/ / child component
class Counter extends Component {
  render() {// Call the function passed by the parent component
    return <button onClick={this.props.increment}>+</button>}}Copy the code


React Communicates with non-parent and child components

1. Introduce the Context

Non-parent component data sharing:

In development, a more common way to pass data is through the props property from parent to child

But there are scenarios where some data needs to be shared among multiple components (locale preferences, UI themes, user login status, user information, and so on)

If we define this information in the top-level App and then pass it down, it will be a redundant operation for some components that do not need data in the middle layer.

  • If there are more layers, passing layers is cumbersome and the code is very redundant:
    • ReactProvided aAPI:Context
    • ContextProvides a way to share such values between components without having to explicitly pass them layer by layer through the component treeprops
    • ContextIt is designed to share data that is “global” to a component tree, such as the currently authenticated user, topic, or preferred language

2. Use the Context

React.createContext

  • Purpose: Create a data that needs to be shared globally (data that needs to be communicated across components)
  • Introduction: If a component subscribes to the Context, the component will match the Context from the one closest to itProvider Read to the currentcontextvalue
  • defaultValueIs the component in the top-level lookup processI didn’t find a matchProvider.Then use the default values

Context.Provider

  • Each Context object returns a Provider React component, which allows the consuming component to subscribe to changes to the Context
  • Transfer the value:ProviderTo receive avalueProperty, passed to the consuming component
  • aProviderCan map to multiple consumer components
  • multipleProviderIt can also be nested, with the inner layer overwriting the outer data.
  • whenProvidervalueAll consumer components within it are re-rendered when the value changes

Class.contextType

  • Mounted on theclassOn thecontextTypeProperty is reassigned to a value specified byReact.createContext()To create theContextobject
  • This allows you to usethis.contextTo consume recentlyContextThe value of phi
  • You can access it in any lifecycle, includingrenderIn the function

Context.Consumer

  • hereReactComponents can also be subscribed tocontextThe changes. This will keep you in theFunctional componentComplete the subscription context
  • Here we need function as child
  • This function accepts the currentcontextValue, returns oneReactnode

3. Component communication diagram


React Communication Supplement

1.React slot

React doesn’t have slots because React is too flexible. How do slots work with React?

Those of you who have used Vue know that if we insert content into a component, we can reserve slots in the child component, and the content is determined by the parent component

Children implements the slot function

When a parent uses a child component, it wraps the content that needs to be presented around the child component

In the child component, props. Children [0] is used to get the content to be displayed by the parent component

understand

We talked about this earlier:

  • The JSX code for the return in the Render function will eventually be converted toReact.createElement('tabName', 'config', children)
  • The third argument, children, is the child element we insert into the React sourceChildrenArrOn thepropsProperties of thechildren, so the child component can passprops.childrenTo receive child elements inserted by the parent component
  • Props implements named slots

    When inserting slot content, you will find that you cannot implement inserting content like the specified slot in Vue (named slot).

    React allows you to specify what you want to insert using the props property, and then in a child component, use props to pull the specified JSX element and insert it at the specified location

    conclusion

    • ChildrenUsage scenario: When onlyA default contentIs inserted directly into the child element
    • propsThe specifiedslotUsage scenario: This parameter is used when there are multiple slotspropsIs passed

    2. Expand properties

    If you already have an props object, you can use the expand operator… To pass the entire props object in JSX

    function Profile(props) {
      return (
        <div>{/* Pass the entire props object in JSX. The following two components are equivalent */}<ProfileHeader nickname={props.nickname} level={props.level}/> 
          <ProfileHeader {. props} / >
        </div>)}Copy the code


    Events Event bus

    events

    • Context has been used to share data, but what if there is event passing across components in development?

      • In Vue, we can quickly implement an EventBus through an instance of Vue
      • In React, we can rely on a more used onelibrary eventsTo complete the corresponding operation
    • You can install events using NPM or YARN: YARN Add Events

    • Events API:

      • Create An EventEmitter object.

      • Emit events: eventbus. emit(” event name “, parameter list);

      • Listener: eventBus.addListener(” event name “, listener function);

      • Remove events: eventbus. removeListener(” event name “, listener function);

    // 1. Create global event bus
    const eventBus = new EventEmitter()
    
    // 2. Launch event
    emitHomeEvent() {
      eventBus.emit('sayHello'.'hello home'.123)}// 3
    componentDidMount() {
      eventBus.addListener('sayHello'.this.handleSayHelloListener)
    }
    
    // 4. Uninstallation event
    componentWillUnmount() {
      eventBus.removeListener('sayHello'.this.handleSayHelloListener)
    }
    Copy the code


    refs

    1. How to use ref

    In React development mode, direct manipulation of DOM elements is not required and is not recommended. However, in some special cases, DOM manipulation is required: text selection or media playback; Trigger mandatory animation; Integrate the third-party DOM library;

    • How do you create refs to get the corresponding DOM? There are three ways:

    • Method 1: Pass in a string

      • Pass when in useThis.refs. The string passed inFormat gets the corresponding element
    • Method two: Pass in an object

      • The object is created using react.createref ();

      • When used, the object created has a current attribute which is the corresponding element

    • Method 3: Pass in a function

      • This function calls back when the DOM is mounted, passing in an element object that we can save ourselves

      • To use it, simply retrieve the previously saved element object

    import React, { PureComponent, createRef } from 'react'
    // ...
    constructor(props) {
      super(props)
      this.titleRef = createRef()
      this.titleEl = null
    }
    render() {
      return (
        <div>{/ *<h2 ref=String/object/function mode> hello react</h2>* /}<h2 ref="titleRef">hello react</h2>
          <h2 ref={this.titleRef}>hello react</h2>
          <h2 ref={arg= > (this.titleEl = arg)}>hello react</h2>
          <button onClick={e= >This.changetext ()}> Change the text</button>
        </div>)}changeText() {
      There are three ways to manipulate the DOM through refs
      // Method 1: a string
      this.refs.titleRef.innerHTML = 'hello jean'
      // Method 2: object
      this.titleRef.current.innerHTML = 'hello JavaScript'
      // Method 3: function
      this.titleEl.innerHTML = 'hello TypeScript'
    }
    Copy the code

    2. The type of the ref

    • The value of ref varies depending on the type of node:

    • When the ref attribute is used for HTML elements, the ref created with react.createref () in the constructor receives the underlying DOM element as its current attribute

    • When the REF attribute is used for a custom class component, the REF object receives the component’s mounted instance as its current attribute

    • You cannot use ref attributes on function components because they have no instances

    constructor(props) {
      this.counterRef = createRef()
    }
    
    
    render() {
      return (
        <div>
          <Counter ref={this.counterRef} />
          <button onClick={e= >Enclosing appIncrementCount ()} > APP button</button>
        </div>)}// Get the class component object by ref
    appIncrementCount() {
      // Invoke child component methods
      this.counterRef.current.increment()
    }
    Copy the code

    Functional components do not have instances, so they cannot be retrieved by ref: But at some point, we might want to retrieve a DOM element from a functional component; React.forwardRef = react.forwardref;


    Controlled components and uncontrolled components

    1. Understand controlled components

    • In React, HTML forms are handled differently from normal DOM elements: form elements are usually stored internallystate
    • For example, the following HTML form element:
      • This is the DOM’s default behavior for handling HTML forms, which are submitted to a server and refreshed when the user clicks Submit.
      • React doesn’t forbid this behavior, it’s still valid;
      • However, JavaScript functions are usually used to easily handle form submission and access the form data that the user has filled in;
      • The standard way to achieve this effect is to use “controlled components”;

    2. Basic drill of controlled components

    • In HTML, form elements such as ,

    • In React, mutable state is usually stored in the component’s state property and can only be updated by using setState()

      • We combine the two so thatReactthestateBeing the “unique data source”;
      • Render formReactThe component also controls what happens to the form during user input;
      • beReactForm input elements that control values in this way are calledThe controlled components“;
    • Because the value property is set on the form element, the value displayed will always be this.state.value, making the React state the only data source.

    • Because handleUserameChange executes and updates the React state with each keystroke, the displayed value changes as the user enters

    3. Other drills for controlled components

    • textareaThe label
      • The Texteare tag is similar to the input tag:
    • selectThe label
      • The select tag is also easy to use, except that it does not need the selected attribute to control which one is selected. Instead, it matches the value of state.
    • Processing multiple inputs
      • Multiprocessing can operate like single-processing, but requires multiple listening methods: Here we can use an ES6 syntax: compute property names

    3. Uncontrolled Components (Understood)

    • React recommends using controlled components to handle form data in most cases:

      • In a controlled component, form data is managed by the React component;

      • Another alternative is to use uncontrolled components, in which the form data is handed over to DOM nodes for processing;

    • If we want to use data from uncontrolled components, we need to use the REF to get the form data from the DOM node

      • Let’s do a simple exercise:

      • Use ref to get input elements;

      • DefaultValue is usually used to set the defaultValue in uncontrolled components

      • Understanding can



    High order component

    1. Understand higher-order functions

    • What are higher-order components? It’s very similar to a higher-order function, and we can start by reviewing what a higher-order function is

    • A Wikipedia definition of a higher-order function that meets at least one of the following criteria:

      • Takes one or more functions as input

      • Output a function

    • Common filter, Map, and Reduce functions in JavaScript are all higher-order functions

    • So what are higher-order components?

      • Higher-order Components, HOC for short
      • The official definition: a higher-order component is one that takes a component and returns a new component
    • We can parse it as follows:

      • First, a higher-order component is not itself a component, but a function
      • Second, this function takes a component and returns a component

    2. Definition of higher-order components

    • Higher-order component calls look something like:

    • Higher-order functions are written like this


    • Component name problem:

      • In ES6, class names can be omitted from class expressions
      • Any component name can passdisplayNameTo modify the

    Higher-order components are not part of the React API, but are design patterns based on the composite features of React

    Higher-order components are common in some React third-party libraries:

    • Like connect in Redux (we’ll talk about that later)
    • For example, withRouter in react-Router (more on that later)

    3. Application scenarios of advanced components

    Application 1: Enhancement of props

    • Add new props without modifying the original code

    • Use higher-order components to share Context

    Application two: render judgment authentication

    • In development, we might encounter a scenario like this:

      • Some pages must be logged in successfully to enter;

      • If the user fails to log in, the login page is displayed.

    • At this point, we can use higher-order components for authentication

    Application 3: Lifecycle hijacking

    • We can also use higher-order functions to hijack the lifecycle and do our own logic in the lifecycle:

    4. Meaning of higher-order components

    • We’ll find that some React code can be handled more elegantly with higher-order components

    • Higher-order components can be used to perform common functions in multiple components

    • In fact, the early React model provided mixins as a way to reuse components. ** is no longer recommended: **

      • Mixins can be interdependent and coupled to each other, which is not conducive to code maintenance
      • Methods in different mixins can conflict with each other
      • There are so many mixins that components can sense and even deal with them, which can snowball in code complexity
    • Of course, HOC has some drawbacks of its own:

      • HOC needs to be wrapped or nested on top of the original components, and if you use HOC in large amounts, you get a lot of nesting, which makes debugging very difficult

      • HOC can hijack props and can cause conflict if conventions are not followed

    • Hooks were groundbreaking in that they solved many of the problems that existed before React

    • Such as this pointing problems, such as hoc’s nesting complexity, and so on

    4. Forward of ref (get functional component DOM)

    • In the front we learnrefAs said before,refCannot be applied to functional components:
      • Because the functional component has no instance, the corresponding component object cannot be retrieved
    • However, in development we might want toGets the DOM of an element in a functional componentWhat should we do at this time?
      • Method 1: Pass the REF attribute directly (wrong)
      • Method 2:throughForwardRef higher order function


    Portals

    The use of the Portals

    • In some cases, weYou want to render content independent of the parent componentAnd evenIndependent of the DOM element currently mounted to(The default is mount toidforroottheDOMOn the element)
    • PortalProvides a way to render child nodes to DOM nodes that exist outside the parent component
      • A parameter:childIs any renderable React child element, such as an element, string, or fragment;
      • Parameters of the two:containerIs a DOM element
      • ReactDOM.createPortal(child, container)

    • In general, when you return an element from the render method of a component, the element is mounted to its nearest parent in the DOM node
    • However, sometimes it is beneficial to insert child elements at different locations in a DOM node


    Fragment

    The use of fragments

    • In previous development, we always wrapped a div root element around content returned from a component

    • We want to be able to not render this and how does the root div do that?

      • useFragment


      • Fragment allows you to group sublists without adding extra nodes to the DOM day

    • React also provides the Fragment phrase:

      • Phrasal use: <>

      • The drop-down to view


      • Note: We cannot use phrasal methods if we need to add attributes or keys to a Fragment


    StrictMode

    StrictMode is introduced

    • StrictMode is a tool for highlighting potential problems in your application

      • Like fragments, StrictMode does not render any visible UI
      • It triggers additional checks and warnings for its descendant elements
      • Strict mode checking runs only in development mode;They do not affect production builds
    • Strict mode can be enabled for any part of the application:

      • No strict schema checking is run on Header and Footer components

      • However, ComponentOne and ComponentTwo and all their descendants will be checked

    What does strict mode check for?

    What exactly is detected?

    1. Identify unsafe lifecycles

    2. Use the outdated REF API

    3. Use the deprecated findDOMNode method

      • In the React API, you could do thisfindDOMNodeTo get the DOM, which is no longer recommended
    4. Check for unexpected side effects

      • This component’s constructor is called twice

      • This is done deliberately in strict mode to let you see if some of the logic written here has any side effects when called multiple times

      • In a production environment, it is not called twice

    5. Detect stale context APIS

      • Earlier contexts were used by declaring Context objects with static properties, returning Context objects with getChildContext, and so on

      • At present, this method is not recommended, you can learn to understand its use

    Mind mapping