A programming specification. React and Redux use the idea of functional programming. Common programming specifications:

  • Imperative programming: care about solving the problem step by step, telling the browser what to do
  • Object-oriented programming: encapsulation, inheritance, polymorphism
  • Event-driven programming: Subscription and firing of events
  • Functional programming:

A programming specification, will be encapsulated as a function of functions are first class citizens, as well as other data types can be used for assignment, mass participation, the return value of the other functions, functional programming of five features: 1: pure functions: the same input will have the same output, completely independent functions and without side effects No side effect is to point to: Operations inside a function have no effect on the outside

// is a pure function
    function add(x,y){
        return x + y
    }
    // The output is uncertain, not a pure function
    function random(x){
        return Math.random() * x
    }
    // Has side effects, not pure functions
    function setColor(el,color){
        el.style.color = color ;
    }
    // The output is uncertain, has side effects, is not pure function
    var count = 0;
    function addCount(x){
        count+=x;
        return count;
    }
Copy the code

2: immutability: Once created, data cannot be modified. If it needs to be modified, a copy must be made. Purpose: To ensure data stability. Prevent dependent data from being modified unknowingly, resulting in exceptions

    1. Unlike const, the properties of data defined by const can still be modified
    1. Similar to Object.freeze, data freezes. However, the deep properties of the freeze data may be modified
    1. Immutable. Js A data immutable library in JS
  • 3: higher-order functions: functions can be used as parameters or return values, for example, array. map, reduce, and filter
  • 4: Combination divides functions into small reusable pure functions, and combines these small reusable pure functions into large functions.
  • Compose: The received parameters are executed from back to front

Principle of JSX: Since the core idea of React is virtual DOM, the principle of the virtual DOM is to simulate the real DOM with JS objects, compare the differences between two virtual DOM, and apply the differences between the two virtual DOM to the real DOM. DOM elements have only three structures: tags, attributes, and child elements. ReactJS extends the syntax of native JS by using javascript objects to describe all HTML, which is very long and unstructured. JSX allows the JS language to support this way of writing HTML code in JS

JSX cannot be parsed directly by the browser, so a tool like Babel is needed to translate JSX into a method called React. CreateElement, which handles arguments as JSX objects based on createElement. Render the JSX object to the page as a dynamically created DOM

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world! '
);
Copy the code

Render (JSX, callback); render (JSX, callback);

Benefits of the virtual DOM: the virtual DOM is fast, the diff algorithm is very powerful, and the direct DOM operation consumes a lot of performance

Rendering the virtual DOM for the first time the first rendering process is long, JSX parses, generates the virtual DOM tree, and eventually calls DOM to draw the view through various calculations. It is clear that if you use HTML directly, you can create elements directly, which is faster, and the white screen time is shorter. The extra layer of computation and memory consumption is definitely a performance drain

So let’s say what we need now is to change a title copy, a virtual DOM and we need to call setState to update that. React does not know what our state will change. It needs to be updated after diff changes are confirmed layer by layer. So it would be more straightforward to modify the CONTENT of the DOM without the diff.

So why use the virtual DOM at all? In our project, the requirements must be more than just changing a title. The advantage of the virtual DOM comes when we need to update elements in a large number of separate pages.

  • First of all, we can avoid a lot of DOM manipulation. DOM manipulation is actually a process of finding the DOM in the page element, which also needs to find the DOM from the root element, and then manipulate it. The code for this procedure is not robust, and if the logic is complex, it will obviously be complicated to implement through DOM manipulation
  • Secondly, the virtual DOM allows our rendering and logic to be managed separately. The React virtual DOM has the concept of a component-mode policy. The entire DOM tree is fragmented. And shouldComponentUpdate can be used to actively interrupt the update stream by adding a flag for components that don’t need to be updated. You can also avoid unnecessary updates
  • The virtual DOM is a JS object that can be cross-platform
  • Virtual DOM is a unified centralized management of DOM, which is more stable and efficient

Diff algorithm What is the diff algorithm?

  • The diff algorithm is the core of the virtual DOM. When data is modified through setState, a complete virtual DOM tree will be created in memory, and targeted updates will be made by comparing the differences between the old and new trees. Diff is an algorithm that compares the differences between two objects.
  • Diff can be used in other scenarios besides virtual DOM tree comparisons, such as version control, which is often used

Optimization strategy of diff algorithm

The same-level comparison strategy only compares the same level and ignores the movement of elements at the kua level. The traditional diff algorithm requires a two-level loop to compare each two nodes. After the same-level comparison strategy is established, nodes are only compared to nodes at the same level. If there is a real movement of elements across the hierarchy, the old elements are removed and created in the new location.

The unique identification policy has improved time performance despite the same-layer comparison policy. However, if two elements of the same type are compared, it is impossible to determine the exact movement of position by type alone. So we need to add a unique identifier to each element to identify and distinguish the nodes. Key is used to make the DIff algorithm more accurate and avoid performance loss

Component pattern strategy

Updating the virtual DOM relies on tree traversal to find the target node that needs to be updated. Let’s say we only need to update one child node, but we have to diff layer by layer from the root node to compare two complete virtual DOM trees. This is a performance drain.

But if you split the child nodes into a separate module, you can call only the diff for that separate module. This is the component pattern, which fragments the entire virtual DOM tree

If we need to update A/D nodes at the same time, we can add A label for B1 node that does not need to be updated to avoid performance loss caused by unnecessary updates. That’s what shouldComponentUpdate does

The realization of the diff

  • If the new and old nodes are different, create or delete them directly
  • When the old and new nodes are the same:
    • First: compare properties and events
    • Second: recursive than sub – level lists
    • If both the old node and the new node have child lists, the comparison is performed in the child lists
    • If the new node does, and the old node does not, the child is created
    • If the new node does not exist, the old node is deleted

The comparison of sub-level lists is the difficulty of DIFF, and its comparison process is as follows:

  • First, the four nodes at both ends are compared in pairs
  • If they do not match, start key comparison
  • If the key matches, the node is moved and updated
  • If the key does not match, add a node in the corresponding position
  • After all the comparisons are completed, delete or add the remaining nodes

Some optimization schemes for diff comparison

  1. Props to pass

When the value of props is a reference type, use reference pass instead of pass directly. Diff loops through the object layer by layer because reference types are not equal when compared, even if the object attributes are identical. Wasted performance. When passing by reference, changes to the data do not modify the source object, and new objects should be created following the principle of immutable data. This reduces the performance loss of diff

  1. The use of the key

Add a unique identity to each node by using a key. When a list needs to be moved on the same level, it avoids element re-rendering and improves diff performance. Different keys can cause nodes to be judged as not being of the same class.

  1. componentization

Componentization is a means of fragmenting the virtual DOM tree, enabling local updates that reduce the number of nodes that trigger diff. Component creation is more complex than diff comparison, avoiding excessive componentization, such as lifecycle execution, component comparison, and so on. For static elements with low reuse rates it is better to use element nodes directly. Components that do not require a life cycle can be written as stateless components (depending on state).

React Fiber q: Why is React Fiber available? Because React updates and loads components synchronously, many things are done during this process, such as calling lifecycle functions, comparing two virtual DOM’s, and applying the virtual DOM to the real DOM to complete the update. This process is completely synchronous, which means that the main thread of the browser is completely occupied by React. There is no problem with a small number of components, but there is a problem with a large number of components. Assuming that it takes a millisecond to load a component, 200 components in a project take 200ms, and if the user enters something on the page at this point, the browser has no time to process it. This can cause the page to stagnate, and after the browser has processed the React component’s update and load, the page will click through with all the user input, which can affect the user experience

What React Fiber does is it takes the whole synchronization process apart and fragments it. Although the overall completion time is still very long, the completion of each section gives other tasks a chance to execute. After the completion of the section, if there is a task with a higher priority to execute, the operation with a higher priority will be executed first. If there is no further execution. Maintaining the data structure in each fragment is called Fiber

Q 2: How will React Fiber affect existing usage? First of all, the Fiber update process is divided into two phases: render and Commit. The first phase is to find which DOM needs to be updated, and this process is allowed to be interrupted. After a task execution segment is complete, it goes back to see if there are higher priority tasks that need to be executed. If the execution is interrupted by a higher-priority task, it will need to be executed again, so the render phase will be called multiple times in its lifecycle. In the COMMIT phase, DOM updates are completed without interruption.

Life cycle function before render:

  • componentWillMount
  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • Lifecycle functions for the COMMIT phase
  • componentDidMount
  • componentDidUpdate
  • componentDidUnmount

Two new lifecycle functions

  • GetDerivedStateFromProps (nextState, prevState) is a pure function whose output depends entirely on the input. Finally, the expected state changes are calculated based on nextState and prevState, and the return value is sent to setState
  • GetSnapshotBeforeUpdate () render returns a snapshot as the third parameter to DidUpdate

The advantages of the JSX

  • JSX executes faster because it is optimized after being compiled into JavaScript code.
  • It is type-safe and errors can be found during compilation.
  • Using JSX to write templates is much easier and faster.

SetState in React setState is an important method for managing state in React. It has three characteristics

  • SetState does not immediately modify the state in the React component
  • In React, setState({key:value}) is used to update data in state. This.state. key = XXX can only change the value of data in state.
  • SetState causes a component update process to redraw the view
  • SetState (shouldComponentUpdate, componentWillUpdate, Render, componentDidUpdate) is not updated until render is called. If shouldComponentUpdate returns false, the render function is not called. This.state is also not updated until the next time Render is triggered
  • Multiple setState calls have the effect of merging

React has four component modes

  • Class components (container components) components handle logic such as event clicks, Ajax requests, and lifecycle functions
  • Function component (UI component, stateless component) The data in the component is completely controlled by external props, only the Render function, no lifecycle
  • High order component
    • Is a function that takes a component and returns a new component
    • Functions with their own state can solve the problems of component reuse, this confusion in class, and logic complexity of life cycle
    • Lots of hooks are provided to solve different things. For example, use estate and useEffect
  • The render property uses a prop with a value of function to pass components that need to be rendered dynamically

Question 1: Why does Redux exist? React is a one-way data flow. Only the parent can update components. There is no data backflow capability. If the project has a lot of data and the interaction between modules is complex, this effect cannot be achieved simply through the flow of state before the parent and child components, so a mechanism is needed to manage state uniformly. Placing state at the top of the component gives you the flexibility to distribute state as needed to various components in the project. This mechanism is called Redux

About Redux:

  • Redux is a mechanism used by React to centrally manage all data
  • Redux stores all of the project’s data in a store
  • The only way a component can change state is by calling the Store’s Dispatch () method and dispatching an action that is processed by the corresponding Reducer and returns newState
  • The component dispatches actions to the store rather than notifying the component directly
  • The component refreshes its view by subscribing to the store’s state

The core API of Redux

  • CreateStore: Creates a store
  • Store. dispatch: Sends Action content to the store
  • Store. getStore: Gets the data in the store
  • Store. Subscribe: Automatically updates after store data changes

Q2: What is the rationale and workflow for Redux?

The components dispatch actions to the Store, and the Store sends state and actions to the reducer. The reducer revises data (setState) and returns nerState. Each component updates its view by subscribing to state in the Store

React-redux workflow

  • The function of React- Redux is to integrate store directly into the props at the top of the React application, as long as each component accesses the props at the top

  • React-redux divides components into container components and UI components

    • Container components: Components handle logic, such as click events, interface requests, changing state, and other functions besides render, such as life cycles. Class components

    • UI component: only responsible for display and interaction, internal does not handle logic, state is completely controlled by external props, only render function, no life cycle. It can be written as a stateless component (just a function)

Because what react-Redux does is put store at the top of your application. Provider is the component at the top, passing store as an argument

<Provider store = {store}>
    		<App />
<Provider>
Copy the code

The purpose of this component is to give all components access to the data in Redux

2, connect

  • connect(mapStateToProps, mapDispatchToProps)(MyComponent)
  • MapStateToProps: Map data from state to props so that the data can be accessed using this.props. Key to complete the rendering
  • MapDispatchToProps: Converts various dispatches to props. This.props. Fn can be accessed.

The use of redux-thunk/redux-sage, on which part

After actions and before data is processed by reducer, there are many asynchronous operations that need to be done, such as Ajax sending and receiving data and then entering the Reducer role between actions and stores