React learning portal

In order to get a better reading experience, please visit the original address: Portal

A, React Profile


What are React

React is an internal project originated in Facebook, because Facebook was for all JavaScript MVC framework on the market are not satisfied, so simply write a set of their own, to set up Instagram. After doing it, I find this stuff quite easy to use, so in May 2013 open source .

Here we need a little attention to the library (Library) and framework (Framework) the difference is, React itself is a JavaScript library for building user interfaces , and we usually say React framework actually refers React / React-router React-redux and combination of, the essential difference is that embodies libraries and frameworks control:

  • "Library" is a collection of specific good package, available to developers to use and is a collection (methods and functions) specific to a hand, the library has no control over, is that users complete control over itself;
  • "Frame" as the name suggests is a framework, based on their characteristics will provide a more complete solution to the user, if the user selects a set of framework, then we need to make certain to adapt the framework itself.

Why React?

This is a very interesting question, let me confused and upset. Since the time I was still in school trying to use Vue build a simple blog system, smooth learning curve, so only some basic HTML / CSS code through a period of time I will be able to get started learning, but learning React, progress becomes relatively slow .. part of the reason is because React innovative development model, and I am at a loss of JSX syntax (vegetables is the original sin).

Vue authors, especially rain Brook answer "Vue advantage and React What are?" In the know almost mentioned this question:

Here I can be generous to admit, if you want to later years on the historical position, React is certainly higher than the Vue. In fact, I, as a developer, but also sincerely admire Jordan Walke, Sebastian Markbage like this, people from the development model proposed level groundbreaking new direction.

React from the start position is to put forward new ideas UI development. Pete Hunt the year when most began to promote React slogan called "Rethinking Best Practices", such a position makes React to open some new ideas, attracted a group of core users like tossing early, and on this basis through community iterative It spawned many of today be regarded as common sense React developer pattern. This is a great place to React, Vue and there was a lot of places are directly inspired by the React. React dare to do such an attempt, because it is Facebook. Such a body mass of companies in infrastructure to enhance the quality level of earnings is huge, and Facebook's engineers are smart enough to rely on wages and dinner, change his / her habits is not a problem. The external promotion, it is "change the industry" emboldened one kind of big companies have.

Compared to "Why React?" Grounds, praised'd obviously some more (React truly groundbreaking development model) React in.

Because the thought React component of it? No. I think with this concept with the number of micro-services like a little similar, which is thought to belong to an era of advances in computer engineering, is a new solution for a mature team proposed an inevitable trend. Whether it is popular Angular / Vue or React, both natural supports the concept of component-based.

That is because React outstanding performance it? I think no. Perhaps React newborn because of its unique and efficient virtual DOM design, front-end can be a meteoric rise in the political arena, but now the front-end technology have matured to the primary key (I do not know, I talk nonsense ..), compared to a lot of places from data, are able to actually see the performance difference React with other frameworks is not particularly large. In the usual development and embodied in such contrast obvious difference in speed, there is no much use.

Also see the view, saying React suitable for large-scale building projects. From what I understand not much, I know React system has many natural constraints, as well as some of the unwritten agreement, which seems to be the default SpringBoot provide the user with a number of positions, there is a strong natural-engineering , plus some common coding style or reduction, which makes it suitable for some large-scale Java team project. But it can not develop large-scale projects always depends on the person, rather than a kind of framework.

I am convinced that it is more on the grounds that (I not quote): like Java, React system is mature enough, the community is also very active, your problem is very easy to find the answer on the network, and there are some proven practices or wheels to solve a variety of problems. And there is a rather special characteristics React: You can use relatively painless React Native developing native mobile applications.

Two, React core concepts


Virtual DOM (Vitural Document Object Model)

To understand the concept of the "virtual DOM", first of all we need to know what is' DOM. " Let's Forget what pages like, we imagine that we now need to write a program to make changes to the following Markdown documents should be how to do it:

# Title
## subtitle - 1
content - 1
## subtitle - 2
content - 2

For example, I now want content - 2the content to change, then I need to continue to traverse the line by line until the final traverse to it in order to operate, the operation of the content changes are similar, so if I want to look to optimize this operation, most the idea is to make it simple to reduce the height of the tree, to increase efficiency.

DOM concepts

DOM is the Document Object Model English acronym, that the document object model. It is a cross-platform programming language-independent API, which put HTML, XHTML or XML document as a tree structure, each node as an object, these objects can be manipulated programming language, and then change the document structure, mapped to the display of the document. When the beginning of DOM and JavaScript are intertwined, but later they eventually evolved into two separate entities. DOM is designed to be independent of a specific programming language, although most of the time we are using JavaScript to manipulate, but in fact, other languages can (such as Python).

If there are so HTML code:

<html>
  <head>
    <title>文档标题</title>
  </head>
  
  <body>
    <a href="">链接</a>
    <h1>标题</h1>
  </body>
</html>

It eventually should be following the same tree structure:

Discussion class ah method of DOM node type right here, we just need to have a general idea of ​​the DOM just fine.

DOM browser rendering process

We can simply look at the browser DOM rendering process:

  1. Parsing HTML DOM tree establishment;
  2. Parsing CSS, combined DOM tree formed Reander tree;
  3. Render layout tree (Layout / reflow), to determine information about the size, position and the like of each node;
  4. Draw Render Tree (Paint), page rendering pixel information;
  5. The browser layers of information to the GPU, GPU will be layers of synthetic (Composite), displayed on the screen;

Why slow operation DOM

In fact, strictly speaking, is not a simple operation DOM slow, it is slow with certain conditions.

Imagine when multiple operations in a single DOM event loop, it is sometimes desirable JS code can get the latest information immediately DOM node, then had to hang browser JS engine, in turn, call DOM engine, calculated to render the latest DOM, in order to obtain the latest information DOM node, and then re-activate the JS engine to continue follow-up operation.

Can be expected, not only the above-described switching operation of the engine a plurality of times, required times calculated layout, redrawn DOM. In fact paintit is a time-consuming process, however, layoutis a more time-consuming process, we can not determine layoutit must be top-down or bottom-up, and even once layoutwill involve recalculate the entire document layout.

But layoutit is certainly inevitable, so we mainly to minimize the layoutnumber of times.

Therefore, reducing the engine switching frequency, the scale of change is the key to DOM DOM performance optimization program reduced!

Virtual DOM algorithm steps

Virtual DOM is to solve the above problem, its essence is to use JS object to simulate our true DOM tree , its algorithm is as follows:

  1. In JavaScript Object Mapping DOM tree structure is formed, and then constructs a DOM tree with the real tree, which is inserted into the document;
  2. When the state changes, re-construct a new object tree, and then compare (Diff algorithm) with new trees and old trees, recording two trees differences;
  3. The second step in the recorded difference applied to the real DOM tree constructed in step one, the view is updated.

The difference between real and virtual DOM DOM of

Thus we can compare the difference between the two:

  1. Changing the plurality of states, the plurality of nodes when the layout impact, frequent changes but the JS object in memory, and then compare the modified portion disposable real need to change the DOM, and the final redraw typeset in real DOM, reducing excessive multi DOM node layout and redraw loss;
  2. Real DOM frequent typesetting and redraw the efficiency is quite low;
  3. Virtual DOM effectively reduce the large area (real DOM node) and redraw the layout, because in the end the difference between the real DOM, can only render locally (with 2);

DOM calculated using the virtual loss:

(Node fewer) = total loss virtual DOM + CRUD (related to the efficiency of the algorithm Diff) real additions and deletions + DOM difference layout and redraw

Direct loss calculation using the DOM true:

Total loss = true full CRUD + DOM (probably more nodes) layout and redraw

Diff algorithm

Core virtual DOM is that Diff, it should automatically help you calculate those adjustments, then only modify the region should be adjusted, the savings rate is not running this "little speed", but the speed of development / maintenance speed / logical extent concise and other "overall speed."

But virtual DOM is fast in relative terms, where reference @尤雨溪is greatly in question know almost "said the online operation DOM real slow, but the test results than React faster, and why? "The answer is a word of it:

Do not so naive as to think that Virtual DOM is fast, diff is not free, batching MVVM can do it, and when the final patch is not to use the native API. Virtual DOM real value in my opinion is never a performance, but it is 1) as a function of type of UI programmatically opened the door; 2) can be rendered to the backend than the DOM, such as ReactNative.

Diff can be divided into three types:

  • Tree Diff: old and new two DOM tree, the contrast layer by layer process, is the Tree Diff, layer by layer when the DOM is completed whole pieces contrast, all the elements need to be updated as needed, must be able to be found;
  • Component Diff: performing time Tree Diff of each layer, the contrast component level, called Component Diff:
    • If the contrast before and after, the same type of component, it is temporarily considered this component does not need to be updated;
    • If you compare the before and after different types of components, you need to remove the old components, create new components, and appended to the page;
  • Element Diff: When performing assembly contrast, if the same type of two components, it is necessary to compare the element level, which is called Element Diff;

三、Hello World


  • Quote from: http: //www.ruanyifeng.com/blog/2015/03/react.html - Ruan Yifeng - React Getting Started tutorial examples

React page source used, the structure is as follows (direct operation):

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Hello React!</title>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>

<div id="example"></div>
<script type="text/babel">
    ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('example')
    );
</script>

</body>
</html>

The code above there are two caveats. First of all, the last <script>label typeattribute text/babel. This is because React unique JSX grammar, is not compatible with JavaScript. Any use of JSX place, should be added type="text/babel".

Secondly, a common code above the three libraries: react.js, react-dom.jsand Browser.js, they must first be loaded. Among them, react.jsis the core library React, react-dom.jsprovide functions related to the DOM, Browser.jsis the role of grammar JSX into JavaScript, this step is very time consuming, when in fact the line, it should be placed in the server to complete.

$ babel src --out-dir build

The above command will srcsubdirectory jsfile syntax conversion, file transcoded in all buildsubdirectories.

ReactDOM.render()

React ReactDOM.render is the most basic method for the templates into HTML language, and insert the specified DOM node.

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('example')
);

The above code is a h1header, the insertion examplenode, results are as follows:

JSX grammar

  • Quote from: https: //www.runoob.com/react/react-jsx.html - RUNOOB.COM - React JSX

On a code, HTML language written directly in the JavaScript language, without any quotation marks, that's JSX syntax that allows mixing HTML and JavaScript to write. Let's look at the following piece of code:

const element = <h1>Hello, world!</h1>;

With different browser DOM element, which is in fact an element React ordinary objects, React to ensure that the browser DOM DOM data content and React elements remain the same. To React elements are rendered to the root DOM node, we will render it to the page they are passed through to ReactDOM.render () method:

var myDivElement = <div className="foo" />;
ReactDOM.render(myDivElement, document.getElementById('example'));

JSX looks similar to HTML, you can nest a plurality of HTML tags in the code above, but requires the use of an divelement surrounding it.

JavaScript expression

We can use JavaScript expressions in the JSX. Expressions written in curly braces {} in. Examples are as follows:

ReactDOM.render(
    <div>
      <h1>{1+1}</h1>
    </div>
    ,
    document.getElementById('example')
);

JSX not be used in the if else statements, may be used Conditional (ternary operator) expression instead. The following examples if the variable i is equal to 1 browser output to true , if the modified value of i is output to false .

ReactDOM.render(
    <div>
      <h1>{i == 1 ? 'True!' : 'False'}</h1>
    </div>
    ,
    document.getElementById('example')
);

style

React recommended to use inline styles. We can use camelCase syntax to set inline styles. React automatically added after a specified digital element PX . The following example demonstrates for the h1 add elements myStyle inline style:

var myStyle = {
    fontSize: 100,
    color: '#FF0000'
};
ReactDOM.render(
    <h1 style = {myStyle}>菜鸟教程</h1>,
    document.getElementById('example')
);

Note

Notes need to write in braces, examples are as follows:

ReactDOM.render(
    <div>
    <h1>菜鸟教程</h1>
    {/*注释...*/}
     </div>,
    document.getElementById('example')
);

Array

JSX allow the insertion of template array, the array will automatically expand to all members:

var arr = [
  <h1>菜鸟教程</h1>,
  <h2>学的不仅是技术,更是梦想!</h2>,
];
ReactDOM.render(
  <div>{arr}</div>,
  document.getElementById('example')
);

Reference material


  1. http://www.ruanyifeng.com/blog/2015/03/react.html - React Getting Started tutorial examples - Ruan Yifeng
  2. https://www.jianshu.com/p/60100985dd7f - the difference between the front end of the frame and the library
  3. https://www.zhihu.com/question/301860721/answer/545031906 - Vue advantage and React, respectively, what is?
  4. https://zhuanlan.zhihu.com/p/22184194 - you really understand DOM yet?
  5. https://developer.mozilla.org/zh-CN/docs/Web/API/Document_Object_Model/Introduction - DOM Overview
  6. https://blog.huteming.site/posts/e0c41c5f/ - Why Virtual DOM faster

By convention a sticky tail:

Welcome to reprint, please indicate the source!
Independent domain name blog: wmyskxz.com
Jane book ID: @ I do not have three heart
GitHub: wmyskxz
welcome attention to the public micro signal: wmyskxz
share their learning & learning materials & living
friend wants to communicate can also add qq group: 3,382,693
Money

Guess you like

Origin www.cnblogs.com/wmyskxz/p/11681955.html