A deep understanding of the principles of the JavaScript React framework

Source: Internet
Author: User
This article mainly introduces the principle of the React framework of JavaScript, including its comparison with AngularJS. If you need a friend, please refer to the following: if you asked me about React two months ago, I may say this:

  • Where is my template? What are the crazy things about HTML in javascript? JSX is very strange! Fire on it. Let's get rid of it!

That's because I didn't understand it.

I swear, React is definitely on the right track. Please let me know.

Good old MVC

The root of all evil in an interactive application is the management status.
The "traditional" approach is the MVC Architecture or some variants.

MVC suggests that your model is the only source of truth-where all States live.
The view is derived from the model and must be synchronized.
When the mode changes, it is not viewed.

Finally, user interaction is captured by the Controller, which updates the model.
So far, everything is fine.

Rendering the view when the model changes

This looks quite simple. First, we need to describe the view-how it converts the model state to the DOM. Then, when a user performs any operation, we need to update the model and re-render the entire page... right? Not so fast. Unfortunately, this is not so direct, for the following two reasons:

  • DOM actually has a certain State, such as the content in a text input box. If you completely invalidate your DOM for re-rendering, the content will be lost.
  • DOM operations (such as deleting and inserting nodes) are really slow. Frequent rendering may cause serious performance problems.

So what if we keep the model and view synchronized while avoiding these problems?
Data Binding

In the past three years, the most common multi-framework feature introduced to solve this problem is data binding.

Data Binding can automatically synchronize models and views. Normally, objects and DOM are represented in JavaScript.

It will let you declare the dependencies between various blocks in the application to package this step together. Status changes will spread throughout the application, and all dependent blocks will be automatically updated.

Let's take a look at how a famous framework actually works.

Knockout

Knockout advocates using the MVVM (Model-View-view model) method, and helps you implement the "View" section:

// View (a template)

First name:

Last name:

Hello, !// ViewModel (diplay data... and logic?)var ViewModel = function(first, last) { this.firstName = ko.observable(first); this.lastName = ko.observable(last); this.fullName = ko.pureComputed(function() { // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName. return this.firstName() + " " + this.lastName(); }, this);};

This is the case. No matter whether the input value is changed, it changes in the span. You never need to write code to bind it. So cool, huh?

But wait, isn't the model the source of truth? What about the view model's status? How does it know that the model has changed? Interesting question.

Angular

Angular adopts the method of keeping the model and view synchronized to describe the data binding. This is described in the document:

But should a view be directly connected to a model? So they will soon be tightly coupled?

In any case, let's take a look at the hello world example with obligation:

// View (a template) 

Name: Hello {{hello.fullName()}}!

// Controller angular.module('helloApp', []) .controller('HelloController', function() { var hello = this; hello.fullName = function() { return hello.firstName + hello.lastName; };});

In this example, it seems that the controller is in a State and has behavior similar to a model-or maybe a view model? Assuming that the model is elsewhere, how does it maintain synchronization with the controller?

My head started to hurt a bit.
Data Binding Problems

Data Binding works well in small cases. However, as your application grows, you may encounter the following problems.

Declared dependencies will soon introduce Loops

The most common problem to be dealt with is to deal with the changing side effects in the status. This figure is from the introduction of Flux. It explains how dependency is implemented:

Can you predict what changes will happen when a model changes? When dependencies change, it is difficult for you to reason for code that can be executed in any order.
Human separation of template and presentation logic

What role does a view play? It plays the role of displaying data to users. What role does the view model assume? It also plays the role of displaying data to users? What's the difference? No!

  • There is no doubt that the template splits the count ~ Pete Hunt

Finally, the view component should be able to operate its data and display the data in the required format. Then, all template languages are inherently flawed: They never achieve the same performance and functionality as the code.

Simple: {{# each }}, ng-repeat and databind = "foreach" are all poor replacements for some native and trivial transactions in JavaScript. And they will not go further. Therefore, they do not provide filters or mappings for you.

Data Binding is a new rendering technique.

What is the Holy Land? We will not discuss it any more. What everyone always wants is to re-render the entire application when the state changes. In this way, we don't have to deal with the root cause of all the troubles: The status will always change over time-given any specific status, we can simply describe what the app looks like.

Okay, the problem is clear. Dude, I hope some of my big masters can set up a super-talented developer group to really solve this problem...
Embracing Facebook's React

It turns out that they did. React implements a virtual DOM, a powerful weapon that brings us the Holy Grail.
What is a virtual DOM?

I'm glad you asked this question? Let's take a look at a simple React example.

var Hello = React.createClass({   render: function() {    return 

Hello {this.props.name}

; }});React.render( , document.getElementById('container'));

This is all the APIs of a React component. You must have a rendering method. Complicated, huh?

OK,

What does that mean? That's not JavaScript! By the way, it is not.

Your new partner, JSX

This code is actually written in JSX. It is a superset of JavaScript and contains the syntax used to define components. The above code will be compiled into JavaScript, so it will actually become:

var Hello = React.createClass({displayName: "Hello",   render: function() {    return React.createElement("p", null, "Hello ", this.props.name);  }});React.render(React.createElement(Hello, {name: "World"}), document.getElementById('container'));

Do you understand this code for calling createElement? These objects constitute the Implementation of Virtual DOM.

Simple: React first assembles the entire application structure in the memory. Then it will replace the structure with the actual DOM node and insert it into the browser's DOM.

Okay, but what is the purpose of compiling HTML with these strange createElement functions?

Virtual DOM is fast

As we have discussed, DOM operations are too costly, so they must be completed in as little time as possible.

The React virtual DOM makes the comparison of the two DOM structures faster, and can precisely find the changes between them. in this way, React can calculate the minimum changes required to update the DOM.

To be honest, React can compare two DOM trees to find the minimum set of operations to be executed. This has two meanings:

  1. If a text input box is re-rendered, React will know its content and it will not touch that input box. There will be no state loss!
  2. Compared with virtual DOM, the overhead is not expensive, so we can compare it with other methods. When it is ready to make actual modifications to the DOM, it only performs the minimum number of operations. There is no additional drag-and-drop layout!

So should we remember the two questions about re-rendering the entire app when the status changes?

This is all the past steps.

React maps status to DOM

In React, rendering and comparison of virtual DOM are only magical parts. Its excellent performance makes it possible for us to simplify the organization of many architectures. How simple is it?

The React component is a function of idempotence (A idempotent operation is characterized by the same impact of any multiple executions as that of a single execution. They can describe your UI at any real-time point .~ Pete Hunt, React: Rethink Best Practices

Simple idempotent functions.

The React component is such a thing, really. It maps the current application status to the DOM. You also have all the capabilities of JavaScript to describe your UI-loop, function, scope, combination, and module-not a poor template language.

var CommentList = React.createClass({  render: function() {  var commentNodes = this.props.data.map(function (comment) {   return (    
 
       {comment.text}    
    );  });  return (   

{commentNodes}

); }}); var CommentBox = React.createClass({ render: function() { return (

Comments

); }}); React.render( , document.getElementById('content'));

Use React today

React is a little daunting at first. It proposes a model change that is too big, which is a bit uncomfortable. However, when you start to use it, its advantages become clearer.

React documentation is excellent. You should try it according to the tutorial. I'm sure that if you give it a chance, you will fall in love with her.

Happy coding!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.