1. The life cycle

  • Mounting (Mounting stage)
    • constructorThe constructor, which is executed first, is usually in the constructorInitialize the state objectOr giveCustom method binding to this
    • getDerivedStateFromProps: static getDerivedStateFromProps(nextProps, prevState)This is a static method when weReceived a new property and wanted to modify state, can be usedgetDerivedStateFromProps
    • render: renderThe function isPure functionsReturns only what needs to be rendered and should not include any other business logic.Can return nativeDOM,ReactComponents,Fragment,Portals, strings and numbers,BooleanandnullThe content such as
    • componentDidMount: called after the component is loaded, at which point weAvailable toDOMNode and operationFor example,Canvas and SVGThe operation,Server request.To subscribe toYou can write it all in here, but remember incomponentWillUnmountUnsubscribe from
  • Updating (update phase)
    • getDerivedStateFromProps: This method is inBoth the update and mount phases may be called
    • shouldComponentUpdate: shouldComponentUpdate(nextProps, nextState), has two parametersnextPropsandnextStateWhich represents the new properties and changesstate.Returns a Boolean value.trueThe representation will trigger a re-render,falseIndicates that rerendering will not be triggered, return by defaulttrue, we usually use this lifecycle toOptimize React program performance
    • renderThe: update phase also triggers this lifecycle
    • getSnapshotBeforeUpdate: getSnapshotBeforeUpdate(prevProps, prevState), this methodinrenderAfter that,componentDidUpdateBefore the call, has two parametersprevPropsandprevStateWhich represents the preceding property and the precedingstate.This function has a return value, which is passed as the third argumentcomponentDidUpdateIf you do not want the return value, you can return itnull.This lifecycle must be associated withcomponentDidUpdateCollocation is used
    • componentDidUpdate: componentDidUpdate(prevProps, prevState, snapshot), the method ingetSnapshotBeforeUpdateMethod is then called with three argumentsprevProps.prevState.snapshotTheta is before thetapropsBefore,state, andsnapshot. The third parameter isgetSnapshotBeforeUpdateThe returned,Needed if certain callback functions are firedDOMElement to migrate the process of comparison or calculation togetSnapshotBeforeUpdateAnd then incomponentDidUpdateTriggers a callback or status update in the.
  • Unmounting (uninstall stage)
    • componentWillUnmount: is called when our component is uninstalled or destroyed. We can do this in this functionClear some timers, cancel network requests, and clear invalid DOM elementsWait for the garbage to be removed

2. How to implement the React component communication

  • Parent to child: The parent component can communicate with the child component by passing props
  • Child component communicates with parent component:**props+ callbacks are passed from parent to child componentspropsTo communicate with thispropsFor a function that is scoped by the parent itself, the child calls this function, passing the information that the child wants to pass as a parameter to the parent’s scope
  • Sibling component communication: Find the common parent node of the two sibling nodes, and use the above two methods to forward information by the parent node for communication
  • Communication across hierarchies: **Context** Is designed to share data that is “global” to a tree of components,For example, the currently authenticated user, topic, or preferred language, for global data across multiple layers throughContextCommunication is perfect
  • Publish/subscribe pattern: Publishers publish events, subscribers listen for events and react to them, we can introduceeventModule communication
  • Global state management tools: ** withReduxorMobxGlobal state management tools such as **, which maintain a global state centerStoreAnd generate new states based on different events

3. A. hooks b. hooks C. hooks D. hooks

React Hooks: Components should be written purely as functions, using Hooks to “hook” external code in if they need external functions and side effects

Hooks are always named with the use prefix for easy identification. If you want to use the XXX function, the hook is named usexxx. React has four default hooks that are most commonly used

  • useState(): const [buttonText, setButtonText] = useState("Click me, please").useState()This function takes an initial value of the state as an argument, as in the example above, the initial value is the button literal. This function returns an array, the array ofFirst memberIs a variable,Points to the current value of the state.The second member is a function that updates the state. The convention issetThe variable name prefixed with the state
  • useContext():const AppContext = React.createContext({});If needed between componentsShared state, can be useduseContext()
  • useReducer():

const [state, dispatch] = useReducer(reducer, initialState); It takes the initial values of the Reducer function and state as parameters and returns an array. The first member of the array is the current value of the state, and the second member is the Dispatch function that sends the action

  • useEffect(): is used to introduce an operation that has side effectsRequest data from the server. Before, in thecomponentDidMountThe code in there, can now be put inuseEffect(). Accept two parameters. The first argument is a function in which the code for the asynchronous operation is put. The second argument is an array that givesEffectAs soon as this array changes,useEffect()It will be executed. The second parameter can be omitted and is executed every time the component is rendereduseEffect().
const Person = ({ personId }) => { const [loading, setLoading] = useState(true); const [person, setPerson] = useState({}); // useEffect() is executed whenever the component parameter personId changes. UseEffect () is also executed the first time the component is rendered. useEffect(() => { setLoading(true); fetch(`https://swapi.co/api/people/${personId}/`) .then(response => response.json()) .then(data => { setPerson(data); setLoading(false); }); }, [personId]) if (loading === true) { return <p>Loading ... </p> } return <div> <p>You're viewing: {person.name}</p> <p>Height: {person.height}</p> <p>Mass: {person.mass}</p> </div> }Copy the code

How does React reuse components

There are three mainstream technologies for component abstraction:

  • Higher-order components: property broker, reverse inheritance
  • Rendering attributes
  • react-hooks

4. The react

  1. React is componentized, and components are updated via status
  2. The difference between JSX and HTML: In JSX, the hump nomenclature
  3. Refs callback
  • ReactAnother setting is also supportedrefsIs called a “callback.refs“. It helps you to be moreFine-grained control over when refs are set and unset.
  • As opposed to transmissioncreateRef()To create therefProperty, you’re passing a function. In this functionacceptReactComponent instance orHTML DOMElement as a parameterSo that they can be stored and accessed elsewhere
  1. SetState benefits
    1. Good encapsulation
    2. Data is separated from presentation
    3. Cascade refresh

5.react-router

  • Exact attribute: WhenexactforfalseFor example, “/” matches “/”, “/ home “, and “/ home/ “. whenexactfortrue, / only matches /, and /home cannot be matched.

This section describes react Router V5

Chinese is introduced

import React, { Component } from 'react'; import { BrowserRouter,Route,Switch } from 'react-router-dom' import App from '.. /pages/App' import Introduction from '.. /pages/Introduction' class Client extends Component { render() { return ( <BrowserRouter> <Switch> <Route component={App} exact path="/" /> <Route path="/intro/:langId" component={Introduction} /> </Switch> </BrowserRouter> );  } } export default Client;Copy the code

6. redux

  • connect: used toGenerate container components from UI components.connectConnect the two components.connectThe method takes two parameters:mapStateToPropsandmapDispatchToProps. They define the business logic of the UI components.The former is responsible for the input logicstateParameters that map to UI components (props), which is responsible for the output logic that maps user actions on UI components toAction.
    • mapStateToProps():Create an externalstateObject to (UI component)propsObject mapping. Will the subscriptionStoreAnd every timestateWhen updated, it will automatically recalculate the parameters of the UI component, triggering a rerendering of the UI component. Its first argument is alwaysstateObject, you can also use a second parameter to represent the container componentpropsObject.
    • mapDispatchToProps()Is:connectThe second argument to the function,Used to set UI component parameters tostore.dispatchMapping of methods. That is, it defines which user actions should be treated asActionAnd send it toStore. It can be a function or it can be an object
      • ifmapDispatchToPropsTheta is a function, you get thetadispatchandownPropsThe props object for the container component
      • ifmapDispatchToPropsIs an object whose key name is also an argument of the same name to the corresponding UI component. The key value should be a function that will be treated asAction creatorAnd the returnedActionbyReduxAutomatically send

Extension: 1. How to perform asynchronous operations in Redux?

Of course, we can make requests directly in componentDidmount without redux.

However, in a project of a certain scale, the above method is difficult to manage the asynchronous flow, usually we will use Redux’s asynchronous middleware for asynchronous processing.

Redux-thunk, Redux-Saga, Redux-Observable, observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Redux-Thunk, Redux-Saga, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable

2. Redux workflow

The entire workflow:

  1. First, the user issues an Action (via the View), which is delivered using the Dispatch method.
  2. The Store then automatically calls the Reducer with two parameters: the current State and the received Action, and the Reducer returns the new State
  3. If the State changes, the Store calls the listener to update the View.

Redux tutorial: github.com/kenberkeley…

7.React FiberWhat is the

React Fiber is a fragmented update process, and the execution process is shown below. After each update process, control is handed back to the React task coordination module to see if there are other urgent tasks to do, if not, continue updating, and if there are urgent tasks to do, do them.

The data structure that maintains each shard is called Fiber.

With a shard in place, the call stack of the update process looks like the figure below, with each trough in the middle representing the execution of a particular shard, and each peak being the time to return control at the end of the shard.

As the update process can be interrupted, the React Fiber update process is divided into two phases: the first Phase Reconciliation Phase and the second Commit Phase.

In the Reconciliation Phase, React Fiber will figure out which DOM needs to be updated. This Phase can be interrupted. But when it comes to the second Commit Phase, it’s time to push through DOM updates without interruption.

In React Fiber, the lifecycle functions in phase 1 can be called multiple times during a single load and update!

After using React Fiber, be sure to check the lifecycle functions associated with phase 1 to see if there is any logic that assumes that they are only called once during an update. If so, change it.

React loading performance optimization

  1. inHTMLWithin the implementationLoadingState or skeleton screen;
  2. Remove the outreachcss;
  3. Cache infrastructure;
  4. Using dynamicpolyfill;
  5. useSplitChunksPluginSplit common code;
  6. Use correctlyWebpack 4.0Tree Shaking;
  7. Using dynamicimport, split the page code, reduce the first screen JS volume;
  8. Compiled intoES2015+, improve the efficiency of code operation and reduce the volume;
  9. uselazyloadplaceholderImprove the loading experience.

Refer to React 16 Loading Performance Optimization Guide

9. The plugin:

  • Redux-logger: A better tip
  • redux-devtools-extension

Link: React interview questions

10. Internationalization language issues

The React language component react-Intl has dropped the addLocalData method, instead of using the intlAPI

Intl API related introduction

How to use React-Intl

import React , { Component }from 'react'; import { Button } from 'antd'; import './App.css'; import {IntlProvider ,FormattedMessage} from 'react-intl'; /* react-intl imports */ // import en from 'react-intl/locale-data/en'; // import en from 'react-intl/locale-data/ en '; //addGlobalData Is deprecated import zh_CN from "./local/zh_CN" import en_US from "./local/en_US" class App extends Component  { constructor(props) { super(props); this.state = { lang: navigator.language.indexOf('zh') ! = = 1? 'zh' : 'en', }; } changeLanguage() { this.setState({ lang: this.state.lang==='zh'? 'en':'zh' }) } render() { let messages = {} messages['en'] = en_US; messages['zh'] = zh_CN; return ( <IntlProvider locale={this.state.lang} messages={messages[this.state.lang]}> <div className="App"> <Button type="primary" onClick={() => this.changeLanguage()}>Button</Button> <FormattedMessage id="hello" /> </div> </IntlProvider> ); } } export default App;Copy the code