A deep understanding of the principles of JavaScript's react framework

Source: Internet
Author: User
Tags bind

This article mainly introduces the principle of JavaScript react framework, including its comparison with ANGULARJS, the need for friends can refer to the following

If you asked me two months ago what I thought of react, I would probably say:

Where is my template? What crazy things does html in JavaScript do? Jsx It's very strange to open up! Fire on it, destroy it!

That's because I didn't understand it.

I swear, react is on the right track, please listen to me.

Good old MVC

In an interactive application all evils are rooted in the state of management.

The "traditional" approach is the MVC architecture, or some variants.

MVC suggests that your model is the only source of testing truth-all the states that live there.

The view originates from the model and must remain synchronized.

When the pattern changes, so no view.

Finally, user interaction is captured by the controller, which updates the model.

So far, everything is fine.

When the model changes, it needs to be rendered on the view

This looks pretty simple. First, we need to describe the view--how it transforms the model state to the DOM. Then, as soon as the user happens, we need to update the model and render the entire page ... Is that right? Not so fast. Unfortunately, this is not so straightforward because of the following two reasons:

The DOM actually has a state, like the contents of a text input box. If you completely void your DOM for rendering, such content will be lost.

DOM operations (like deleting and inserting nodes) are really slow. Frequent rendering can cause serious performance problems.

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

Data binding

For the past three years, the most commonly used framework for solving this problem is data binding.

Data binding can automatically keep the model and view synchronized. Objects and Dom are usually represented in JavaScript.

It will package this synchronization by letting you declare dependencies between the blocks in your application. State changes will spread throughout the application, and all dependencies will be updated automatically.

Let's take a look at how it actually works in some well-known frameworks.

Knockout

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

?

1 2 3 4 5 6 7 8 9 10 11 12-13 View (a template) <p>first name: <input data-bind= "Value:firstname"/></p> <p>last name: <i Nput data-bind= "Value:lastname"/></p>

And that's it. Regardless of the change, the input values are changing in span. You never have to write code to bind it. How cool is that, huh?

But wait, isn't the model the source of the truth? Does the view model here ever get its state? How does it know that the model has changed? Interesting question.

Angular

Angular describes data binding in a way that keeps the model and view synchronized. As described in the document:

But... Should the view directly interact with the model? So they are tightly coupled soon?

Anyway, let's take a look at the Hello World example:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16 View (a template) <div ng-controller= "Hellocontroller as Hello" > <label>Name:</label> <input Type= "text" ng-model= "Hello.firstname" > <input type= "text" ng-model= "Hello.lastname" >

From this example, it looks like the controller has a state and has a similar behavior to the model-or perhaps a view model? Assuming the model is in other places, how does it maintain synchronization with the controller?

My head is starting to hurt a little.

Issues with data binding

Data binding works fine in a small example. However, as your application becomes larger, you may experience the following problems.

Declaration of dependency will quickly introduce loops

The most common problem is dealing with the side effects of changes in the state. This figure comes from the Flux introduction, which explains how dependence begins to dig a hole:

Can you predict what happens when a model changes? When dependencies change, it is difficult to infer the cause of the problem for code that can be executed in any order.

Template and presentation logic are artificially separated

What role does the view play? It plays the role of displaying data to the user. What is the role of the view model? Does it play the role of displaying data to the user? What's the difference? Not at all!

There is no doubt that the template has been torn apart by the count ~ Pete Hunt

Finally, the view component should be able to manipulate its data and display the data in the format it needs. Then, all the template languages are inherently flawed: they never achieve the same expressiveness and functionality as code.

Very simply, {{# each}}, Ng-repeat and databind= "foreach" are clumsy substitutes for some native and trivial things in JavaScript. And they will not go further further. So they don't provide you with filters or mappings.

Data binding is a trick that should be rendered again

What is the holy Grail no longer our discussion list. What everyone always wants is to be able to render the entire application again when the state changes. In this way, we don't have to deal with the root of all the problems: the state always changes over time-given any particular state, we can simply describe what the application will look like.

Well, the problem is clear. Dude, I want some big companies to be able to really solve this problem by having a super talented developer team ...

Embracing Facebook's react

It turns out they did it. React implements a virtual DOM, a weapon that brings us to the holy Grail.

What is a virtual dom?

I'm glad you asked. Let's take a look at a simple react example.

?

1 2 3 4 5 6 var Hello = React.createclass ({render:function () {return <div>hello {this.props.name}</div>;}}); React.render (

This is all the APIs for a react component. You have to have a rendering method. It's complicated, huh?

OK, but

What is the meaning? That's not JavaScript! Yes, it's not.

Your new partner, JSX.

This code is actually written in JSX, a superset of JavaScript that contains syntax for defining components. The above code is compiled into JavaScript, so it actually becomes:

?

1 2 3 4 5 6 var Hello = React.createclass ({displayName: "Hello", Render:function () {return react.createelement ("div", null, "Hello" , this.props.name); } }); React.render (React.createelement (Hello, {name: "World"}), document.getElementById (' container '));

Do you understand the code for the createelement call? These objects form the implementation of the virtual DOM.

Very simple: react first in the memory of the application of the entire structure of the Assembly. It then replaces the structure with the actual DOM node and inserts it into the browser's DOM.

OK, but what is the purpose of writing HTML with these strange createelement functions?

The virtual DOM is fast

As we've already discussed, manipulating the DOM is ridiculously expensive, so it has to be done in as little time as possible.

The REACT virtual DOM makes the two DOM structures really fast and can find out exactly what's changed between them. Thus, react can calculate the minimum changes needed to update the DOM.

To be honest, react can compare two DOM trees to find the minimum set of operations it wants to perform. This has two meanings:

If an input box with text is react, it will know what it has, and it will not touch that input box. There will be no state to be lost!

It's not expensive to spend on virtual DOM, so we want to be able to do that. When it is ready to make actual changes to the DOM, it does only the smallest amount of action. No extra drag to slow the layout of the risk!

So are we going to remember these two questions about the whole app again when the state changes?

It's all in the past.

React map State to DOM

Only virtual DOM rendering and alignment are magical parts of react. Its excellent performance enables us to have a much simpler consolidation infrastructure. How simple is it?

A react component is a function of idempotent (a power operation characterized by the effect that any number of executions have on the same effect as one execution). They can describe your UI at any point in time. ~ Pete Hunt, react: Rethinking Best practices

A simple idempotent function.

React component that's the whole thing, really. It maps the current application state to the DOM. And you also have the full capabilities of JavaScript to describe your ui--loops, functions, scopes, combinations, modules-not a crappy template language.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 var commentlist = React.createclass ({render:function () {var commentnodes = This.props.data.map (function (comment) {ret Urn (<comment author={comment.author}> {comment.text} </Comment>); }); Return (<div classname= "Commentlist" > {commentnodes} </div>);   } }); var Commentbox = React.createclass ({render:function () {return (<div classname= "Commentbox" >

You start using react today.

React was a bit intimidating at first. It puts forward a really big change in the pattern, which is always a bit uncomfortable. However, when you start using it, the advantage becomes clearer.

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

Code Happy!

Related Article

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.