Writing in the front

React, as one of the two front-end frameworks in China, is a must for us to master, and it is essential for us to enter big factories. This paper introduces the basics and principles of React in detail, so that you can have a deeper understanding and insight into React

To eat: Primary front-end taste index: 😋😋😋😋😋

1. React event mechanism ⭐⭐⭐⭐⭐

Reasons for adopting event composition mode:

  1. If too many event handlers are bound to the DOM, the overall page response and memory footprint can suffer.
  2. React binds events to root for unified management, which is equivalent to event delegation, to prevent events from being directly bound to native DOM elements, resulting in uncontrollable situations
  3. React wants to implement a full browser framework, and to achieve this goal it needs to provide a consistent event system across browsers to smooth out differences between browsers.

steps

  • Event binding: React does not bind the Click time to the DOM when the user adds functions for onClick. Instead, listen for all supported events at root (similar to using a unified event listener, which maintains a map to hold all component internal event listeners and handlers)
  • Event triggering: When an event occurs and bubbles up to root, the function is specified to execute using the uniform dispatch function dispatchEvent

The characteristics of

  • Most events are brokered to root for performance optimization purposes
  • For each type of event, there is a unified dispatch function, dispatchEvent
  • Event objects are synthetic objects, not native, that simulate all the capabilities of DOM events
  • Event.nativeevent gets the nativeEvent object
  • When passing a parameter, the event is received as the last parameter

The difference between a composite event and a native event

  1. It’s written differently. In a native event, the event name is lowercase, while in React, the event name is hump
  2. PreventDefault behavior is different. In HTML, the default behavior to prevent events is return false, whereas React must call preventDefault.
  3. Using JSX syntax requires passing in a function as an event handler instead of a string;
  4. React’s event mechanism is divided into two phases: event registration and event distribution. All events are registered with root, and when triggered, they bubble up to root in the form of event bubbles. React then encapsulates the event to a formal function handler.

2. What is JSX: ⭐⭐⭐⭐⭐

React.createElement('tag'.null, child1, child2, child3)
Copy the code
  • JSX is a syntactic extension of JavaScript that is fully capable of JavaScript
  • JSX is compiled by Babel as: react.createElement (), with the first argument being the label name, the second attribute, and the third child
  • JSX syntactic sugar allows front-end developers to create a virtual DOM using the htML-like tag syntax we’re most familiar with. This function returns a VNode, which is then rendered by patch

3. Communicate with the React component ⭐⭐⭐⭐ port

1. Use props to convey required information

Context: In React, you can use the context function to pass data across layers of a component tree. Context is used to pass data across layers of a component tree. Since a component’s Context is composed of the Context object returned by getChildContext () from all components in the parent chain, the component can access the properties of the Context provided by all components in the parent chain. Application scenarios: Language, theme and other logic is not complex but needs to be passed down layer by layer:

  • First create a context with React. CreateContext (the default) : XXX
  • Then wrap the component with the xxx.provider with a value={value to change and receive}
  • ContextType = XXX (contextType = XXX); contextType = XXX (contextType = XXX);
  • (The function component wraps the content in XXX.Consumer, and uses a function to get the value.)

3. Use redux to manage global status

4. Customize the publish and subscribe mode

import { EventEmitter } from 'events'; component1:this.eventEmitter = emitter.addListener('changeMessage'.(message) = > {
    this.setState({ message, }); }); component2: handleClick =(message) = > {
        emitter.emit('changeMessage', message);
    };
Copy the code

5. Send parameters through routes

params
  this.props.history.push({pathname:"/path/"+ name}); Read parameters with:this.props.match.params.name
query
  this.props.history.push({pathname:"/query".query: { name : 'sunny'}}); Read parameters with:this.props.location.query.name
state
  this.props.history.push({pathname:"/sort ".state : { name : 'sunny'}}); Read parameters with:this.props.location.query.state
search
  this.props.history.push({pathname:`/web/search? id${row.id}`}); Read parameters with:this.props.location.search
Copy the code

The advantages and disadvantages:

  • Params does not lose page refresh parameters in both HashRouter and BrowserRouter routes
  • The state page refresh parameter is not lost in BrowserRouter and is lost in HashRouter routes
  • Query: Refresh page parameters are lost in both HashRouter and BrowserRouter routes
  • Query and state can pass objects

6. ref

Use the React ref attribute to obtain the entire subcomponent instance. Remember that hooks must bind to the DOM, or use useImperativeHandle

4. Talk about advanced components and render props ⭐⭐⭐⭐⭐

Higher-order components:

HOC is a component design pattern in which HOC takes a component with additional parameters (if needed) and returns a new component. HOC is a pure function with no side effects. 1. Pass through all props {… This.props} 2. Adding the XXX attribute Advantage: logic reuse, does not affect the internal logic of wrapped components. Disadvantages: increases component layers, such as pass-through cost, pass-through coverage, etc

Render prop:

Render Prop is a simple technique for using a prop shared code with a function between React components. Components with Render Prop accept a function that returns the React element, injecting render logic into the components: The data is shared, the code is reused, the state in the component is passed to the caller as props, and the rendering logic is handed to the caller. Disadvantages: Unable to access data outside the return statement, not elegant nesting

5. React lifecycle ⭐⭐⭐⭐⭐

Component mount phase:

1. The constructor:

  • If it is not explicitly defined, there is a default constructor
  • If we explicitly define a constructor, we must execute super(props) in the constructor, in order to inherit this from the parent, otherwise we cannot get this in the constructor.
  • If state is not initialized or method binding is not performed, there is no need to implement the Constructor for the React component.

Constructor usually does only two things:

  • Initialize the state of the component
  • Bind this to the event handler method

2. getDerivedStateFromProps

  • Is a static method, so you can’t use this in this function
  • There are two parameters, props and state, which refer to the new parameter received and the state object of the current component
  • This function returns an object to update the current state object, or null if no update is required.
  • This function is called when loading, when new props are received, or when setState and forceUpdate are called. This can be used if you want to change state when you receive a new attribute.

3. render

Render is the core method in React. A component must have this method, which renders the component based on its state and properties props

4. componentDidMount

Is called immediately after the component is mounted (inserted into the DOM tree).

This phase usually performs the following operations:

  • Perform DOM-dependent operations;
  • Sending network requests; (Official recommendation)
  • Add a subscription message (unsubscribe at componentWillUnmount)

Component update phase:

Update re-rendering is triggered when the props of the component changes, or when setState/forceUpdate is called inside the component, which can happen multiple times

1. getDerivedStateFromProps

2. shouldComponentUpdate

  shouldComponentUpdate(nextProps, nextState) {
    if(nextState,count ! = =this.state.count) {
      return true;  // Can render
    }
    return false // Do not repeat rendering
  }
Copy the code
  • SCU returns true by default, meaning React rerenders all child components by default
  • It must be used with immutable values
  • SCU can not be used at first, and then consider using it when there are performance problems

SCU summary: SCU is a hook function, can be in inside the custom whether or not to render the logic, it returns a Boolean value, if there is no custom each time the default returns false, this life cycle function can be used to make does not need to update the child components don’t update to improve rendering performance, just because of this, the react of immutable value principle is very important, The setState should be kept unchanged every time, otherwise shallow comparisons can cause problems with array and object changes when using SCU or PureComponent

3. render

4. getSnapshotBeforeUpdate

  • There are two parameters prevProps and prevState, representing the props and state before the update
  • It enables the component to capture some information (for example, scroll position) from the DOM before changes are made.
  • Any return value from this lifecycle method is passed as an argument to componentDidUpdate().

5. componentDidUpdate

The updated lifecycle of the component allows manipulation of the DOM

This method takes three parameters:

  • PrevProps: props before the update
  • PrevState: Indicates the state before update
  • Snapshot: getSnapshotBeforeUpdate() Return value of the life cycle

Component uninstallation phase

1. componentWillUnmount()

SetState should not be used in this method because once the component is unloaded, it will not be loaded again and will not be re-rendered.

Function:

  • Clear timer, cancel network request or clear
  • Unsubscribe subscriptions created in componentDidMount(), etc.

1. ComponentDidCatch (Error, info)

This life cycle is invoked after a descendant component throws an error.

It receives two arguments:

  • Error: A thrown error.
  • Info: Object with componentStack key, which contains stack information about component raising errors

6. What are controlled components and uncontrolled components ⭐⭐⭐⭐

Controlled components: When a form is used to collect user input, elements such as < SELECT >< texteArea > are bound to a change event. When the state of the form changes, the onChange event is triggered to update the state of the component. This type of component is called a controlled component in React. In a controlled component, the state rendered by the component corresponds to its value or checked property. Disadvantages: The React component manages the values of form elements. When you have multiple input fields or multiple React components, you have to write event handlers for each of them if you want to get all the values at the same time. This makes the code look bloated.

Uncontrolled components:

The value of input is not controlled by state, but has an initial value defaultValue, which is usually retrieved from the DOM node by ref

Usage Scenarios:

  • You have to manipulate DOM elements manually, which setState can’t do, like file uploads
  • Some rich text editors need to pass in DOM elements

7. What about setState? ⭐ ⭐ ⭐ ⭐ ⭐

Is setState synchronous or asynchronous?

Asynchrony: True where React can control it, such as in React lifecycle events and composited events that merge and delay updates. Synchronize: React can only synchronize updates to events that cannot be controlled, such as native events, such as addEventListener, setTimeout, setInterval, etc.

SetState call procedure:

  1. After calling setState, an enqueueSetState method puts the new state into the component’s state queue and calls enqueueUpdate, passing in the instance object to be updated.
  2. In the enqueueUpdate method, the isBatchingUpdates property of the batchingStrategy object is determined. IsBatchingUpdates is false by default, IsBatchingUpdates identifies whether you are currently in the batch creation/update phase of a component. If it is the turn of execution, the batchedUpdates method is called to initiate the update process directly. (The batchingStrategy is probably the only thing inside React that manages batch updates.)
  3. When React calls batchedUpdate to perform the update action, the lock is set to “locked” (set to true), indicating that “a batch update is in progress.” When the lock is “locked”, any components that need to be updated can only be temporarily placed in the dirtyComponents queue for the next batch update, rather than “jumping the queue” at will. The idea of “task locking” here is the cornerstone of React’s ability to implement orderly batch processing in the face of a large number of states.

What can be hit by batchUpdate:

  • The lifecycle (and the functions it calls)
  • Events registered in React (and functions it calls)
  • React can “manage” the entry

Which cannot hit batchUpdate mechanism:

  • SetTimeout setInterval etc. (and the function it calls)
  • Custom DOM events (and the functions it calls)
  • React “An entrance out of reach”

Immutable value: Do not change state directly, use setState, and do not change the value of the original state

When it is an array:

  this.setState({
    list1: this.state.list1.concat(100),  / / append
    list2: [...this.state.list2, 100]./ / append
    list3: this.state.list3.slice(0.3),  / / interception
    list4: this.state.list4.filter(item= > item > 100),    / / filter
    list5: list5Copy  // Other operations
  })
Copy the code

You can also use slice() to get a copy and then do the operation. Note that you can’t push pop splice on this.state.list directly, which violates immutable values

When being an object:

    this,setState({
      obj1: Object.assign({}, this.state.obj1, {a: 100}),
      obj2: {... this.state.obj2,a: 100}})Copy the code

Note that you cannot attribute this.state.obj directly, as this violates immutable values

7. Why is the props in React read-only? ⭐ ⭐ ⭐ ⭐

Functions can only flow from parent components to child components. React has a strong functional programming philosophy. When it comes to functional programming, one concept comes up: pure functions.

It has several features:

  • Given the same input, always return the same output.
  • There are no side effects.
  • Independent of external state.

This. Props borrows the idea of pure functions. The immutability of props ensures that the same input is displayed on the same page without side effects

8. React Performance optimization ⭐⭐⭐⭐

shouldComponentUpdate

  shouldComponentUpdate(nextProps, nextState) {
    if(nextState,count ! = =this.state.count) {
      return true;  // Can render
    }
    return false // Do not repeat rendering
  }
Copy the code
  1. SCU returns true by default, meaning React rerenders all child components by default
  2. It must be used with immutable values
  3. SCU can not be used at first, and then consider using it when there are performance problems

SCU summary: SCU is a hook function, can be in inside the custom whether or not to render the logic, it returns a Boolean value, if there is no custom each time the default returns false, this life cycle function can be used to make does not need to update the child components don’t update to improve rendering performance, just because of this, the react of immutable value principle is very important, The setState should be kept unchanged every time, otherwise shallow comparisons can cause problems with array and object changes when using SCU or PureComponent

PureComponent in React, when prop or state changes, you can prevent the page from updating by returning false in the shouldComponentUpdate lifecycle function, thus reducing unnecessary render execution. React.PureComponent shouldComponentUpdate automatically. ShouldComponentUpdate () in pureComponent is a shallow comparison, which means that if a reference is made to a datatype, only the same address is compared, not the same address. This avoids generating and comparing the virtual DOM. Achieve the purpose of improving performance

9. What are Fragments: ⭐⭐⭐

  • A common pattern in React is for a component to return multiple elements. Fragments allow you to group sublists without adding additional nodes to the DOM.
  • In React, we need to have a parent element and return the React element from the component. Sometimes adding extra nodes to the DOM can be annoying. With Fragments, we don’t need to add additional nodes to the DOM. We just need to wrap the content with a react. Fragment or short <>

10. Introduce Portal Portal: ⭐⭐⭐

Portal provides an excellent solution for rendering child nodes to DOM nodes that exist outside the parent component

ReactDOM.createPortal(child, container)
Copy the code

The first argument (child) is any renderable React child, such as an element, string, or fragment. The second argument (container) is a DOM element.

Usage Scenarios:

  • The parent component has overflow:hidden and wants to escape from the parent component
  • The z-index value of the parent component is too small
  • Fixed elements should be placed in the body layer for better browser compatibility
return ReactDOM.createPortal(
  this.props.children,
  domNode
);
Copy the code

11. What are the similarities and differences between class components and function components? ⭐ ⭐ ⭐

Similarities:

The React components are the smallest pieces of reusable code that return React elements to render on the page. The results are consistent and can be rewritten

Difference:

  1. Class component is based on object-oriented programming, which focuses on core concepts such as inheritance and life cycle. Function component kernel is functional programming, which is immutable, without side effects, transparent reference and so on.
  2. In terms of performance optimization, the class component mainly relies on shouldComponentUpdate to block rendering to improve performance, while the function component relies on react.Memo to cache rendering results to improve performance.
  3. Class components are much easier to use, and function components are the future of the community, thanks to React Hooks.
  4. Class components are not easy to optimize in the future time slice and concurrent mode due to the complexity of the life cycle. The function component itself is lightweight and simple. Based on Hooks, it provides more fine-grained logic organization and reuse than before, and is better suited for the future development of React.

12. React and Vue difference ⭐⭐⭐⭐

Thing in common:

  • Both keep their focus on the core library, leaving other functions such as routing and global state management to the relevant libraries
  • Each has its own build tool that allows you to get a project template set according to best practices.
  • Both use the Virtual DOM to improve redraw performance
  • Both have the concept of props to allow data transfer between components
  • Both encourage componentized applications, which are broken down into functional modules to improve reusability

Difference:

  1. Data flow: Vue supports bidirectional data binding by default, while React has always advocated one-way data flow
  2. Virtual DOM:
  • Vue claims to be able to calculate Virtual DOM differences faster because it tracks the dependencies of each component during rendering, without having to re-render the entire component tree.
  • With React, all child components are rerendered whenever the state of the application is changed. Of course, this can be achieved by PureComponent/shouldComponentUpdate the lifecycle methods to control, but the Vue see this as the default optimization.
  1. React uses JSX to embrace JS, Vue uses templates to embrace HTML
  2. The principle of monitoring data changes is different
  • Vue knows exactly what the data is doing through getters/setters and hijacking of some functions.
  • React is done by default by comparing references (DIFF), which if not optimized can result in a lot of unnecessary VDOM re-rendering.
  1. Extension aspects:
  • React can be extended with higher-order components
  • Vue needs to be extended through mixins

13. Introduce the virtual DOM and Diff algorithm ⭐⭐⭐⭐⭐

The reason for using the virtual DOM

  • In traditional development, when you manipulate the DOM, you go through the process of building the DOM tree from start to finish. When you manipulate the DOM, you don’t know if there will be any DOM operations. After ten DOM operations, you build ten times.
  • Virtual DOM is to simulate the real DOM node with JavaScript. Js objects represent the DOM structure, and the object records the label, attribute and child node of DOM node. The comparison of DOM changes is done in THE JS layer.
  • The advantage of using JS object to simulate DOM node is that the update of the page can be reflected in THE JS object (virtual DOM) first, and the speed of operating the JS object in memory is obviously faster. After the update is completed, the final JS object will be mapped to the real DOM, which will be drawn by the browser.

The diff algorithm:

Harmonization: the process of converting Virtual DOM tree into actual DOM tree. Diff algorithm is the concrete realization of harmonization.

The diff strategy

React converts O(n^3) complexity to O(n) complexity using three strategies

  1. Strategy 1: Ignore nodes across hierarchies. Two trees only use nodes at the same hierarchy. React does not reuse a DOM node if it crosses hierarchies in two updates.
  2. Strategy 2: By default, two components with the same class generate similar tree structures. Two components with different classes generate different tree structures. Comparison: Two elements of different types produce different trees. If the element changes from div to P, React destroys the div and its descendants and creates a new p and its descendants
  3. Strategy 3: Developers can use key prop to indicate which child elements are stable in different renders, and for a set of child nodes at the same level, they can be distinguished by unique ids.

The Diff process

  1. Starting from the Diff’s entry function reconcileChildFibers, which calls different handlers based on the newChild, or JSX object, type
  2. If the newChild type is object, number, or String, there is only one node at the same level, and the single-node Diff processing is performed. If the newChild type is Array, there are multiple nodes at the same level, and the multi-node Diff processing is performed
  3. In single-node Diff, the existence of the corresponding DOM node is determined first, and if so, the reuse is determined by key and type. If the reuse is possible, the previous copy is returned; if not, the node is deleted and a new one is generated
  4. In the multi-node Diff, there are three cases: node update, node addition or reduction, and node position change. It will judge the situation first and then decide which logic to go to, update, add or delete. In this case, there are two rounds of traversal. Second traversal: Process the remaining nodes that are not part of the update.

14. React how to implement data persistence ⭐⭐⭐

  • When global data is stored with Redux, if the user refreshes the web page, it is wiped clean, such as login information. There is a need for persistent global data storage.
  • The first thing that comes to mind is localStorage. LocalStorage is a data store with no time limit. It can be used to realize persistent storage of data. However, on the basis of using Redux to manage and store global data, using localStorage to read and write data is not only a huge workload, but also prone to error.
  • So redux-persist. Redux-persist caches data from redux’s store into the localStorage of the browser

15. React SSR server render ⭐⭐⭐

Client rendering:

First request HTML, and then download HTML JS/CSS files, wait for JS loading, and then request data to the server, data returned from 0 to complete client rendering

Disadvantages:

  • The first screen load time is slow due to the JS file pull and React code execution during page display.
  • SEO(search engine optimization) is completely helpless, because search engine crawlers only recognize HTML structure content, not JS code content

Server render:

First request HTML, then server request data, render initially on server, return interface with correct content, request JS/CSS, return render the remaining small part

Advantages:

  • Under client rendering, in addition to loading HTML, it also needs to wait for JS/CSS to complete loading, and then execute JS rendering to render the page, during which the user is waiting all the time
  • The server only needs to load the content of the current page, rather than loading the entire JS file at once. The wait time is greatly reduced and the first screen loads faster.

Disadvantages:

  • It is not conducive to the separation of front and rear ends, and the development efficiency is low.
  • Occupies server resources.

16. React.createClass differs from React.Component: ⭐⭐⭐

  1. The function this is self-bound
  • CreateClass creates a component whose this is automatically bound to React for each member function. This in the function is set correctly.
  • React.Com ponent created component, its member function does not automatically binding this, need a developer manual binding, this won’t be able to access to current component instance objects.
  1. The component property type propTypes and its defaultProps property defaultProps are configured differently
  • When a component is created, the properties of the component props and the default properties of the component are configured as properties of the component instance. DefaultProps uses the getDefaultProps method to obtain the default component properties
  • When react.componentconfigures these two corresponding information when creating a component, they are configured as properties of the component class, not as properties of the component instance, which are called static properties of the class.
  1. The initial state of the component is configured differently
  • React.createClass creates a component whose state state is configured using the getInitialState method.
  • React.componentcreates a component whose state state is declared in Constructor as if it were initializing the component properties.

17. React render problem ⭐⭐⭐⭐

Which methods trigger react rerender:

  1. The setState () method is called
  • Render is not triggered when setState is passed null
  1. The parent component is re-rendered
  • As soon as the parent component is rerendered, the child component will be rerendered, triggering render, even if the props of the child component passed in have not changed

What does rerendering render do?

  1. The old and new VNodes are compared, which is called the Diff algorithm.
  2. A depth-first traversal is carried out on the old and new trees, so that each node will have a mark. When it comes to the depth traversal, the node will be compared with the new node tree every time it reaches one or two nodes, and if there is any difference, it will be put into an object
  3. Traverse the difference object, update the VNode according to the response rule according to the type of difference
  4. React’s basic mindset for dealing with render is to rerender the entire application every time there is a change

How does React tell when to rerender components?

  • Component state changes can be made by props changes, or directly through the setState method.
  • The component gets the new state, and React decides if the component should be rerendered. React rerenders the component whenever its state changes.
  • Because the shouldComponentUpdate method in React returns true by default, this is what causes every update to be rerendered
  • Need to override the shouldComponentUpdate method to return true or false depending on the situation to tell React when to re-render and when to skip re-render

18. What are the two modes of the React Router ⭐⭐⭐⭐ port

Hash mode (default)

Such as abc.com/#/user/10

  1. Hash mode is a mode that concatenates the path of the front-end route with a hash sign (#) after the real URL. When the path after the hash # changes, the browser does not re-initiate the request, but rather fires the Hashchange event, which is not included in the HTTP request.
  2. In hash mode, all page hops are performed by the client without the support of the backend, making it more flexible for page interception. However, each URL change is not an HTTP request
  3. A hashchange does not result in a page refresh, so window.onhashchange is used to monitor the hashchange to implement a refresh free jump

H5 history

Such as abc.com/user/10

  1. To change the historical state, you can use the following methods: Back, Forward, and go. To change the historical state, you can use the following methods: pushState; replaceState; This state object can be retrieved via event.state, which allows the page state to be restored
  2. The URL of the front end must be the same as the URL of the back end; otherwise, a 404 error will be reported. Not afraid to go forward, not afraid to go back, but afraid to refresh, F5, (if the back end is not prepared, it will return 404), because the refresh is actually requesting the server.
  3. Simple to use, more beautiful

19. React-router implementation idea: ⭐⭐⭐

Implement the above different client routing ideas based on the history library, and can save historical records, etc., smooth out browser differences, the upper layer is not aware, through the maintenance of the list, every TIME the URL changes in the collection, through the configured routing path, match to the corresponding Component, and render

20. How to configure the react-router to implement route switchover: ⭐⭐⭐

  1. use<Route> component
  2. Use a combination of<Switch>The component and<Route>Component, one<Switch>It’s going to go through all of its children<Route>Element and render only the first element that matches the current address.
  3. use<Link>、<NavLink>、<Redirect>component
  • The Link:<Link>Component to create links in your application. No matter where you render one<Link>Render anchors in the application’s HTML (<a>)
  • NavLink:<NavLink>Will add parameters (CSS styles, etc.) to the rendered element when it matches the current URL.
  • Redirect:<Redirect>Components implement route rescheduling, typically using from and to attributes

21. The difference between the Link tag and the A tag in the react-router ⭐⭐⭐

From the final DOM rendering, both are links, and both are tag differences:

  • <Link>General fit<Route>With react-router, it takes over its default link jump behavior
  • <Link>The “jump” behavior only fires matches<Route>The corresponding page content is updated without refreshing the entire page.

does three things:

  • If you have onclick, do onclick
  • Prevent a tag from default event when click
  • Use history (either history or hash) to jump to the href(to) where the link has changed and the page is not refreshed<a>Tags are simply hyperlinks used to jump from the current page to another page (in the case of non-anchor points) at the href point.

22. React-router How to obtain URL parameters and historical objects (routed values) : ⭐⭐⭐

Get URL parameters:

  1. Route configuration is common, for example:'admin', the method of parameter transmission is as follows:'admin? id='1111''. throughthis.props.location.searchGet URL Gets a string'? id='1111', can use URL, QS, QueryString, browser API URLSearchParams object or their own encapsulation method to resolve the value of the ID.
  2. Dynamic routing:Through this. Props. Match. Params. IdObtain the value of the dynamic route ID part of the URL. In addition, you can also passUseParams (Hooks)In order to get
  3. Pass values via Query or State: Objects can be passed in the TO property of the Link component{pathname:'/admin',query:'111',state:'111'}Through theThis. Props. The location. The state or enclosing props). The location of the queryTo obtain, disadvantages: refresh page data loss

Get the history object:

  1. useHistory();
  2. Get the history object using this.props. History

23. Redux ⭐⭐⭐⭐⭐

Redux is a state management library for React. It is based on Flux and simplifies one-way data flow in React. State management is completely abstracted from React.

Workflow:

  • In React, the component connects to Redux, and if you want to access redux, you need to send an action to the Reducer.
  • When reducer receives the action, the reducer receives the action via the switch… Case syntax compares type in action. When a match is made, updating the corresponding content returns the new state.
  • When the Redux state changes, components connected to the Redux will receive the new state as props. When the component receives these props, it goes into the update phase and rerenders the UI.

Redux’s three principles:

  1. A single data source (a Redux app has only one store) is also a one-way data flow;
  2. State is read-only. (The only way to change state is to trigger an action, which is a generic object that describes events that have occurred.) ;
  3. Use a pure reducer function to modify state.

Redux Middleware:

  • Redux’s middleware provides an extension point after the action is initiated and before the reducer arrives,
  • The data flow from View -> Action -> Reducer -> store was reduced to View -> Action -> Middleware -> Store
  • In this section, you can do some “side effects” such as asynchronous requests, printing logs, and so on
  • The Redux middleware takes an object as a parameter with two fields, Dispatch and getState, representing two functions of the same name on the Redux Store.
  • The Two ends of the Currie function are middewares and Store. dispatch

24. What is the difference between Redux and Vuex, their common idea ⭐⭐⭐⭐

Thing in common:

  1. Store is used to store global state objects.
  2. The state in Store cannot be directly modified (mutation in VUEX and Reducer in REdux), and only synchronous operation is allowed.

Difference:

  1. Vuex removed the concept of Action from Redux. Unlike Redux, which believes that a state change must be triggered by an “action”, Vuex only believes that mutation is needed to trigger a state change at any time. A Redux Action must be an object, whereas Vuex assumes that it only needs to pass the necessary parameters, with no form requirement.
  2. Vuex also weakened the reducer concept in Redux. Reducer reducer reducer reducer reducer reducer reducer reducer reducer reducer reducer reducer reducer reducer reducer reducer reducer reducer In Vuex, the equivalent is mutation, or “transformation,” which simply “transforms” the old state based on the input parameter.

25. What does connect do: ⭐⭐⭐⭐

Connect React and Redux

Access to the state

Connect uses context to get stores in the Provider, and uses store.getState() to get all states in the entire Store tree

use

export default connect(mapStateToProps, mapDispatchToProps)(AppUI); // Decorators can also be used
Copy the code

MapStateToProps: This function maps state to props, so whenever state changes, the new state is remapped to props. That’s how you subscribe to the store.

MapDispatchToProps: Used to map component parameters to the store.dispatch method. Action was triggered to update the Reducer, and then state was updated, causing changes in UI data

24. Introduce hooks, which are different from class components ⭐⭐⭐⭐

Features of function components:

  • No component instance
  • No life cycle
  • There is no state or setState, only props can be received

Problems with class components:

  • Large components are hard to break down, refactor, and test (i.e., classes are hard to break up)
  • The same business logic is scattered into various methods, resulting in logic chaos
  • Reuse logic becomes complex, such as mixins, HOC, Render Props
  • Complex life cycle

React Hooks fix some issues:

  • It is difficult to reuse state logic between components, and hooks allow us to reuse state logic without modifying the component structure
  • Complex components become difficult to understand, such as the many different logic in componentDidMount, while hooks help keep the focus on separations, which allow one logic to be written in a bunch
  • “This” is not in hooks
  • Complex life cycle

⭐⭐⭐⭐⭐

UseState:

UseState is a Hook that allows us to add state to the React function component

const[Current state value, function that sets state value] = react.usestate (initial value)Copy the code

Different from class component state: There can only be one state in a class component. It is common to treat an object as a state, and then represent different states through different attributes of the object. Function components with useState make it easy to create multiple states and are more semantic.

Why useState uses arrays instead of objects: To reduce complexity, return arrays that can be destructed in order, and return objects that can be used more than once that need to be aliased

Effect Hook:

The default function component does not have a life cycle. The function component is a pure function, which is destroyed upon execution and cannot realize its own life cycle. Use Effect Hook to Hook the life cycle into the pure function

useEffect

  • Without dependencies, it will be executed after each render
  • Analog componentDidMount-useEffect dependency []
  • Analog componentDidUpdate-useEffect No dependency, or dependent [A, b]
  • Returns a function in simulated componentWillUnMount-useEffect

Ps:

  • This is not exactly the same as WillUnMount. Instead, the return function will be executed before the next effect is executed
  • If useEffect is currently emulating Mount and Update, the function in return will be executed before the Update

UseEffect allows pure functions to have side effects. Side effects are effects outside of the function, such as setting global timed tasks. Components need side effects, so useEffect needs to be hooked into pure functions

UseEffect and useLayoutEffect differences:

  • Both are used to handle side effects, and the underlying function signatures are exactly the same
  • UseEffect is performed asynchronously after rendering, so it may cause flickering
  • UseLayoutEffect is executed synchronously, before the browser actually renders the content to the interface and then renders it to avoid flickering.
  • That said, it’s best to put dom manipulation into useLayoutEffect to avoid flickering.

UseCallback:

It is mainly used for caching functions. Every time any state change of functional components will cause the whole component to be refreshed. Some functions do not need to be refreshed, so they should be cached to improve performance

UseMemo:

It is used to cache the value of the calculation result, usually for components, to reduce unnecessary updates of components.

useRef

  • Returns a mutable ref object whose.current property is initialized as the parameter passed in.
  • The ref object returned remains the same throughout the life of the component, meaning that the same REF object is returned each time the function component is re-rendered.

Application Scenarios:

  1. Used to get DOM nodes
const btnRef = useRef(null), <button ref={btnRef}>
Copy the code
  1. Get instances of child components (only class components are available)
  2. A global variable in a function component is not declared repeatedly by repeating render, like this.xxx in a class component

useContext:

Receives a context object (the return value of React. CreateContext) and returns the current value of the context

useReducer

The useState alternative takes a Reducer and returns the current state and its accompanying dispatch method

Applicable scenarios:

  • The state logic is complex and contains multiple child values, or the next state depends on the previous state
  • UseReducer can also be used to optimize the performance of components that trigger deep updates

Differences between useReducer and Redux

  • UseReducer is an alternative to useState for complex state changes
  • The useReducer is used to manage the state of a single component. Component communication also needs props
  • Redux is global state management, with multiple components sharing data

Thank you for reading

Thank you very much for reading to the end, if there is any mistake, I hope you can point out, so as not to mislead others. If you think it is helpful to you, I hope you can click a like, add a concern, any question can contact me, I hope we can make progress together.

Finally, I wish you a bright future, we climb each other, high meet 🌈!