Analysis of advanced features of React

react conText

Using API React.createContext returns a component object that can use the structure

  • the first way
    Components wrapped with Provider can get the provider’s value

  • Context. Consumer
    The function is used in the component. The function returns a component. The parameter of the function is the parameter initialized by Context

  • the second way

  1. Wrap all components with Context.Provider
  2. Context created by using static contextType = in the subcomponent will automatically look up and then you can get the value through this.context inside the component

Portals slot

A dom can be inserted under other dom ReactDOM.createPortal (the node that needs to be inserted, the node that needs to be mounted)

React. createPortal(Component, nodeElement)

HOC

  • The main function is to extract state and reuse logic. The operation method can directly use the ES7 decorator
  • Pass in a component to a function, return a component, and extract the common logic from the function
  • For example: each page needs to load data and render the page, then the public data acquisition interface can be extracted and the specified component can be rendered
  • hoc life cycle component's didMount -> hocDidMount -> hocwillMount -> hocwillUnMount -> unMount

HOC has a common problem that props may be repeated

For example:

  1. Each component has a common operation. For example: A component needs to modify the name B component also needs to modify the name to upgrade the state using HOC Pass in the modification event and the passed in value
  2. Loading operation Each component has a loading state Use hoc to receive a loading status and then use this The loading status control shows whether the loading component or the business component
  3. Data request Two sets of the same data request are placed in different display components for rendering, and the operation of obtaining data can be extracted

Mouse movement example All components need to get the mouse movement x y within a certain component

const withMouse = Component => {<!-- -->
return class extends React. Component {<!-- -->
    state = {<!-- -->
        x: 0,
        y: 0
    };
    handleMouseMove = event => {<!-- -->
        this.setState({<!-- -->
            x: event.clientX,
            y: event.clientY
        });
    };
    render() {<!-- -->
        return (
            <div onMouseMove={<!-- -->this.handleMouseMove}>
                <Component {<!-- -->...this.props} mouse={<!-- -->this.state}/>
            </div>
        );
    }
}
}

RenderProps

Surprisingly similar to HOC. There will be no more duplication of props. In fact, it is a callback function to obtain external data

// for example

Put repeated actions inside the component
The component internally calls the external render method to realize that the external component can obtain the internal state of the component so as not to affect the transmission of props

class Mouse extends React. Component {<!-- -->
    static propTypes = {<!-- -->
        // render: required
    };

    state = {<!-- -->
        x:0,
        y:0
    };


    handleMouseMove = (event) => {<!-- -->

        this.setState({<!-- -->
            x: event.clientX,
            y: event.clientY
        })
    };


    render() {<!-- -->

        return (
            <div onMouseMove={<!-- -->this.handleMouseMove}>
                {<!-- -->this.props.render(this.state)}
            </div>
        );
    }
}

Refs Forward

  • The main reason is that it is inconvenient to obtain the ref of the leaf component. Using ref forwarding can accurately obtain the ref of the leaf component
 const ref = React.createRef()
    React.forwardRef((props, ref) => {<!-- -->
        <Component ref={<!-- -->ref}>
    })

ref will become the ref of the leaf component

Fragments

  • Mainly in the code logic to these components will not generate any additional nodes
<>
  <div>hello</div>
</>

React.lazy React.suspense lazy loading

React. lazy(() => import('./Component'));
  1. In the past, webpack packaged everything into one file, resulting in a particularly large file, which is not conducive to code splitting. At this time, code splitting is required
  2. const OtherComponent = React.lazy(() => import('./OtherComponent')); If there are multiple lazy loaded components, the display will be displayed with the longest loading time component
  3. React.suspense parameter fallback content to be displayed during lazy loading

Principle Analysis

  • When the parent component renders to the child component, an asynchronous request is found and an error is thrown directly. The captured result is a promise
  • ComponentDidCatch captures this promise exception pending and renders fallback
  • Re-render when resolve encounters the next asynchronous request and repeats the above operation
  • Until the promise object thrown by the entire parent component will resolve replace loading with the real component

HOOK hook

HOOK provides a series of hooks for functional components

const [value, setValue] = useState();

value is the state state setValue is a function that needs to set a value and directly calls setValue to pass in the value that needs to be set. Can

  1. useEffect Pass in an anonymous function. The anonymous function is equivalent to DidMount and DidUpdate. You can return a function in the anonymous function

The difference between Component and PurComponent

The difference: the former comes with a shallow comparison of props and state to achieve shouldComponentUpdate while the latter does not only need props to change will re-render

  • Disadvantages of PurComponent
    False negative judgments may be generated due to inconsistencies in deep data, so that the interface cannot be updated
    Why it happens: the new object simply refers to the original object, and changing the new object will affect the original object, such as foo = {a: 1} bar = foo bar.a = 2 This time zone comparison foo and bar are the same. The general solution is to use deep copy to refer to immutable and optimize it

Cut and anti-shake

  • Throttle Control triggers once at a specified time Cannot be called more than once within a specified time
  • Debounce Debounce ensures that a function will not be executed a certain amount of time after the last call
  • requestAnimationFrame Throttling The browser will ensure that 60 frames per second can prevent operations exceeding 60 frames per second and limit the flow by itself

setState

Asynchronous processing Adding data multiple times will result in unexpected return of data, which can be processed in the form of functions

Why use asynchronous processing?

  • setState will not immediately change the value of React components and state
  • setState triggers a redraw by triggering a component update
  • The effects of multiple setState function calls will be merged

Reference: Vision published on aoppp.com

syntaxbug.com © 2021 All Rights Reserved.