React in-depth understanding of notes

1. How React works

1、UI = f(data){}

UI is the interface. This interface is the result of function execution. It is based on the concept of functional programming. What we do is to implement this function. Change the UI by changing the parameter data in the function. Change data. Let data drive this function, and this function influences (produces) the UI. So in React, whether you implement a component or perform other functions, you have to implement a function, change the data in the function, and let the data drive the function. This function affects (produces) the UI, that is to say You change the UI by changing the data. This is the philosophy of React.

data is props and state

Developers only need to maintain the variable data state (what) and let the react framework help us handle DOM operations (what).

React calculates how to update the view through the diffing algorithm. The diffing algorithm has a hypothetical premise. The developer will provide an ID to each child of the long list to help the algorithm compare, as shown in the following figure:

react-key

The uniqueness of the node is ensured by the key and repeated rendering is avoided. It can be illustrated by the above figure. React believes that if the keys are the same, then there is no need to recalculate and render, as long as the keys are not the same (such as a new insert If an x ​​node is created), the x node needs to be rendered separately.

Two elements of key in the same set of components

1. The key is unique among sibling nodes.

2. The value of the key is stable, and the value of the key must be fixed. Do not always change the value of the key. In actual development, the value of the key should not be set as the index value of the array, because this is an unstable value. For example, as shown in the figure above, the index value of B was 1 before, but after the change, the index value becomes 2.

3. The ternary expression does not need to be marked with a key, because no matter whether the condition of the ternary expression is established or not, there will be a corresponding value, which will occupy the corresponding position.

Finished rendering process

The initial rendering process is divided into 3 steps.

In the first step, the developer writes React using JSX grammar and babelwill compile JSX into React JS grammar that the browser can recognize. At this point, the general combining webpackperformed locally.

The second step, execute ReactDOM.renderthe function, rendering a virtual DOM.

In the third step, react renders the virtual DOM into a real DOM.

The page update process is also 3 steps.

The first step, when the page needs to be updated by means of declarative call setStateto tell react what data has changed.

In the second step, react automatically calls the render method of the component to render the virtual DOM.

The third step, react will pass diffingalgorithm, compared to the current virtual DOM and need to be updated virtual DOM What is the difference. Then re-render the different parts of the real DOM.

ReactRender

  1. What is modular: From the code point of view, and to analyze the problem, when our programming business logic, divided into different modules to be developed, this can facilitate code reuse ;
  2. What is componentization: From the perspective of UI , to analyze the problem, split a page into some unrelated small components, as our project develops, we will have more and more components in our hands. Finally, we If you want to implement a page that may directly take over the existing components stitching, you can quickly get a complete page, this party will reuse UI elements ; component is a collection of elements ;

What is Virtual DOM (Virtual DOM)

Virtual DOM (VDOM) is a programming concept that means that a virtual view is stored in memory and kept in sync with the "real" DOM ​​through libraries such as ReactDOM. This process is called reconciliation.

This programming method uses React's declarative API: you need to tell React what state you want the view to be in, and React is responsible for ensuring that the DOM matches that state. Therefore, you don't have to complete attribute operations, event handling, and DOM updates by yourself when building your application. React will do all of this for you.

Since "virtual DOM" is more like a pattern than a specific technology, we sometimes use it to mean other things. In the world of React, since both the "virtual DOM" and the React element number are objects used to represent views, they are often associated together. However, React also uses objects called "fibers" to store additional information about the component tree. In React, they are also considered part of the "virtual DOM" implementation.

Are Shadow DOM (Shadow DOM) and Virtual DOM (Virtual DOM) the same concept?

No, they are not the same concept. Shadow DOM is a browser technology that is mainly designed to provide encapsulation for variables and CSS in web components. Virtual DOM is a concept implemented by JavaScript library on top of browser API.

Diff algorithm

  • tree diff: The new and old DOM tree is compared layer by layer, which is called tree diff. Whenever we compare the nodes of all layers from front to back, we must be able to find those elements that need to be updated;
  • Component diff: When comparing each layer, the comparison between components is called component diff; when comparing components, if two components are of the same type, it is temporarily considered that this component does not need to be updated, if the types of components are different , Remove the old component immediately, create a new component, and replace it to the removed position;
  • element diff: In the component, each element should also be compared. Then, the element-level comparison is called element diff;
  • key: key is an attribute that can make a correlation between the DOM node on the page and the object in the virtual DOM;

Fiber is the new engine in React 16. Its main purpose is to enable incremental rendering of the virtual DOM.

React Fiber is a re-implementation of React's core algorithm.

The goal of React Fiber is to improve its applicability to areas such as animation, layout, and gestures. Its most important feature is incremental rendering : it can split the rendering work into multiple blocks and distribute these task blocks to multiple frames for execution.

Other core features include the ability to pause, suspend, or resume work when a new update arrives; the ability to prioritize different types of updates; and new concurrency primitives.

What is reconciliation?

  • reconciliation

    The algorithm used by React to compare two trees. It determines which parts of the tree need to be updated.

    • update

      Changes to the data used to render the React application. Usually the setStateresult. The final result will be a re-render

    The core idea of ​​React's API is to imagine the update as a re-rendering of the entire application. This allows developers to derive declaratively without worrying about how the application efficiently transitions from one state to another (A to B, B to C, C to A, etc.).

    In fact, re-rendering the entire application for each change is only suitable for the simplest application. In actual applications, there will be a very large overhead on performance.

    Reconciliation is the algorithm behind the widely known "virtual DOM".

    • Different component types are considered to generate essentially different trees. React will not try to compare differences, but will directly replace the old tree completely.
    • For the difference comparison of the list, the key is used to optimize the performance. Keys should be stable, predictable and unique.
  • Scheduling

    Scheduling

    • scheduling

      The process of deciding when work should be executed.

    • work

      Any calculation results must be executed. Work is usually the result of an update (eg setState).

      In the current implementation of React, React traverses the tree recursively and calls the render method to update the entire tree in one iteration of the event loop. However, in the future, it will delay some updates to prevent dropped frames.

      This is a common theme in React design. Some popular libraries implement the "push" method, and calculations will be executed when new data arrives. But React insists on the "pull" method, calculations can be postponed until needed.

      React is not a general data processing library. It is just a library designed to build user interfaces. We believe that knowing which calculations are relevant now and which are not content that has a unique place in the application.

      If something is off the screen, we can postpone any logic related to it. If the data arrives faster than the frame rate, then we can merge and update in batches. We can prioritize the work from the user's interaction with the interface (such as an animation of a button click) and the relatively unimportant work behind it (such as remotely loading data to render new content) to prevent dropped frames.

    Summarize the core points as follows:

    • In the UI, not all updates need to take effect immediately. In fact, this is wasteful and may cause dropped frames and affect user experience.
    • Different types of updates have different priorities. An animation update usually needs to be performed faster than an update from the data.
    • A "push"-based solution requires the application (you, the engineer) to decide how to schedule work. And a “pull” approach allows frameworks (such as React) to be smarter to make these decisions for you.

    The main goal of iber is to allow React to enjoy the benefits of scheduling. To be clear, we need to be able to do the following things:

    • Pause the task and be able to resume the task later.
    • Set different priorities for different tasks.
    • Reuse previously completed tasks.
    • You can terminate a task if it is no longer needed.

    In order to do these things, we first need a way to split these tasks into task units. In a sense, these task units are fibers. A fiber represents a task unit .

    view = fn(data)
    

    So rendering a React application is similar to calling a function that contains other function calls.

2. Everything is a component

2.1 The life cycle of a component

React life cycle

Any data obtained between components through props is read-only and cannot be reassigned

The tags in the jsx syntax are not directly rendered on the page, but first converted into React.createElementsuch js code, and then rendered to the page through render

Static methods in es6 class are mounted in the constructorconstructor, and instance methods are mounted in the prototype object

class Person {
    constructor(name,age){
        this.name = name
        this.age = age
    }
    // say 是实例方法
    say(){
        console.log('您好')
    }
    
    // info 是静态方法
    static info = 123 
}

class Chinese extends Person {
    // 使用extends 关键字实现继承,子类的constructor构造函数中,必须显示调用super()方法,这个super表示父类中constructor的引用
    constructor(name,age,color,lang) {
        super(name,age)
    }
}

var p1 = new Person('zs',12)
console.log(p1)

var c1 = new Person('ls',12,'yellow','汉语')
console.log(c1)
c1.say()
console.log(Chinese.info)

The difference between react stateless component and stateful component
Stateless component: Stateless Component is the most basic form of component. Since there is no influence of state, it is purely static display. Generally speaking, various UI libraries are also the component categories that will be developed at the beginning. Such as buttons, labels, input boxes, etc. Its basic structure is properties (props) plus a rendering function (render). Since it does not involve status updates, this type of component has the strongest reusability.

Stateful components: On the basis of stateless components, if the component contains state and the state changes with events or external messages, this constitutes a Stateful Component. Stateful components usually have a lifecycle to trigger state updates at different times. This kind of component is also usually used most often in writing business logic, and the number of states and life cycle mechanisms of the components are different according to different business scenarios.

When to use stateless components? When to use stateful components?

1. If a component only needs to render a fixed page through props passed from the outside world, it is suitable to use the functioncreated stateless component.

2. If a component needs to store its own private data and needs to execute different business logic at different stages of the component, it is suitable to use stateful components.

In React, we usually deal with two types of data through props and state. Props are read-only and can only be set by the parent component. The state is defined in the component and can be changed during the life cycle of the component. Basically, stateless components use props to store data, while stateful components (also called smart components) use state to store data.

In general: Stateless functional writing is better than React.createClass, and React.Component is better than React.createClass. If you can use React.Component to create components, try not to create components in React.createClass form.

There are three ways to create components in React:

  • ES5 writing:React.createClass
  • ES6 writing:React.Component
  • Stateless function writing, also known as pure component

3. Declarative programming

Declarative and imperative

  • Imperative programming: Command the "machine" how to do things (how), so that no matter what you want (what), it will be implemented according to your commands.
  • Declarative programming: Tell the "machine" what you want (what) and let the machine figure out how to do it (how).

jQuery is imperative programming. jQuery lets you use its API to do some things. If the jQuery API changes, the code we write must also change. Because the API has changed, we need to modify the previous API. So this design is very unfriendly.

The code written in React is unlikely to call system-level APIs. On the contrary, we implement some functions and respond. The code we write only declares what we want to do and how to do it. React is done, we don’t need to. To care, even if React's API changes, it will not affect.

3. Advantages and limitations of JSX

1. Put the related codes together for easy maintenance, which is necessary for a single component.
2, renderthe function is a pure function, do not render things, but it is the return of some instructions, and then to operate through these instructions by the React by DOM DOM or virtual, so the results are returned react by the React.createElementresult of

3. In jsx {}can only be an expression, not a statement, because jsx can React.createElementbe rendered in a form converted into babel , but React.createElementthe parameter in jsx can only be an expression, not a statement (such as for loops, if judgment), while jsx the renderfunction {}can not be used push(), reverse()other array method, because the render should be a pure function, pure function should not have side effects, rendering it should be state or the props, if used push(), reverse()other array method, Then it will directly modify the data in the state or props instead of generating new data

Fourth, what to use props and when to use state

image-20181121213406519

Data in React includes: satae and props. Props are data passed from external components, and satae is the internal state of the component. A component's own satae can be used as the data source of props passed to its sub-components, a component If you want to change your state, you can only change your state through setState. A component cannot change its own update state directly by modifying its own props, nor can it modify its own props, because modifying its own props will be messy . Whenever props can handle things, try not to use state.

Using the props passed by the parent as the state of the child will cause the value reference object to affect the problem, that is, if I change the child state, the parent props will be changed accordingly

Five, explain the life cycle of React components in detail

There are three processes in the life cycle of React components:

  • mount: the process from scratch
  • update: re-rendering is divided into state change and props
  • unmount: from there to nothing

Mount process:
getDefaultProps
getInitialState
componentWillMount
render
componentDidMount: This function can only be executed on the browser side, but when using React for server-side rendering, it cannot be executed on the server side (because the string that is highlighted on the server side is basically There is no saying that a DOM-tree is mounted, so it will not be executed),

The update process caused by state changes:

shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate

The update process caused by the parent component wanting to render this component change:

componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate

If the parent component does not need to be re-rendered, shouldComponentUpdate will return a false, so the subsequent componentWillUpdate, render, and componentDidUpdate will not be executed.

Whether it is the declaration period before the render function in the mount process or the update process, the obtained state or props are the data that has not changed before. Only after the render function is the state after the data has changed.

Six, why try to build stateless components

A stateless component is a pure function. Try to make the component a purely functional stateless component, because it can reduce the appearance of some bugs, we should centralize some stateful components (that is, contain state) for management, and let its sub-components It is a stateless component, so it is easy to manage and maintain,

Seven, create a higher-order component (HoC, Higher-Order Component)

HoC high-end component usage scenarios

Use high-level components to share a common function, so you don't have to write the same function code.

8. Communication between components

The parent component passes parameters to the child component in the form of properties, and the child component accepts the parameters passed by the parent component through props

If the child component wants to communicate with the parent component, the child component must call the method passed by the parent component

The communication between sibling components can use the parent component as an intermediary to transfer data (two functions are written in the parent component, and these two functions are respectively passed to the two child components, and then refer to each other)

The communication between any components can be used as an intermediary to transfer data by setting a global variable.

If this project is relatively popular, of course you can also use redux for communication between components.

Guess you like

Origin blog.csdn.net/it_cgq/article/details/84951209