Why the react frame is so hot: react's design idea

Source: Internet
Author: User



Original link: http://mp.weixin.qq.com/s?__biz=MzA5Njc3Njk5NA==&mid=2650528748&idx=1&sn= 4d3093e963ce76c642eb0c5d9a97625b#rd


The origins of react





React comes from Facebook, yes, the website that you've heard of but can't open. Facebook developers were developing an ad system because they were not satisfied with the current MVC framework, so they wrote a UI framework and react. Later because it feels really good to use, so in the 2013 month open source this framework. After a few years of precipitation, react more and more powerful, but also by more and more developers love. React current (2015-05-04) version is 0.14.0, from the version number has not reached the 1.0 version, meaning react is also frequently modified, commonly used in the product also need a certain amount of time. At the March 2015 F8 Developer Conference, Facebook released the React Native, which formally extends react's tentacles to the app. It also developed an atom-based ide-nuclide for react native, which is also open source.



React menacing, great unified lakes and rivers momentum. Front-end developers should keep their enthusiasm for learning new technologies, and it is necessary to familiarize themselves with react related technologies. Below we briefly talk about react related technologies.


The design idea of react


The key to familiarity with a new technology is familiarity with his features and philosophy



The react framework itself and our commonly used JavaScript MVC framework, such as Angularjs,backbone,ember, are not directly comparable. In React's official blog, it is clear that react is not an MVC framework, but a library for building a modular UI and a front-end interface development tool. so at best, it's the V (view) in MVC. React does not reinvent the wheel, but has a lot of disruptive innovations, specific features are as follows:


Write simple and intuitive code


At the react developer Conference at the beginning of the year, React's project manager, Tom Occhino, described React's greatest value,react's greatest value is not high-performance virtual DOM, encapsulated event mechanism, server-side rendering, but declarative, intuitive coding. react claims to enable new features to be developed on the first day of life. Simple coding will allow the novice to quickly get on the ground and also reduce the cost of code maintenance. This feature determines the basis on which react can quickly generate interest and spread widely among developers. The following is a concrete approach to react based on this concept.


Simplify Reusable components


React building the UI is a way to use components rather than a common template. A component is not a new concept, it is an encapsulation of a standalone function or interface that achieves reuse or UI and business loosely coupled purposes.



The modular design concept has been going on for many years, and our common ExtJS, YUI, jQueryUI, Bootstrap, and so on, provide a large number of reusable UI components. For example, use the dialog box component in Bootstrap:





/ / initialization
$(‘#myModal‘).modal({
keyboard: false
};
/ / display
$(‘#myModal‘).modal(‘show‘);
//Close event
$(‘#myModal‘).on(‘hidden.bs.modal‘, function (e) {
// do something...
};





You can see that the components we use often provide a number of interfaces and configurations that allow developers to choose the right usage scenario. The design of these components is complex, the use is more cumbersome, the novice has a certain threshold. The web is also stepping up its efforts to develop standards for components, a unified, simple, and functional, standardized component concept. Let's look at how react is designing the component model and how it differs from the Web component.



The react framework uses a simplified component model, but uses the concept of component more thoroughly. React defines each functional module in the entire UI as a component, and then makes the smaller components larger by combining or nesting them. This practice has been widely implemented on Instagram websites and you can look at the front-end source code for Instagram. The following is a simple example to illustrate the concept of modularity in react. This example comes from React's official website tutorial, which is to complete a simple comment box. This comment box consists of two sections, a comment list and a review form. The display results are as follows:






According to the React module combination design, the comment box component Commentbox is divided into two sub-component modules: Commentlist and Commentform, the code is as follows:





<div className="commentBox">
  <h1>Comments</h1>
  <CommentList data={this.state.data} />
  <CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>





The Commentlist and Commentform components correspond to the following code:





<div className="commentList">
  {commentNodes}
</div>


<form className="commentForm" onSubmit={this.handleSubmit}>
  <input type="text" placeholder="Your name" ref="author" />
  <input type="text" placeholder="Say something..." ref="text" />
  <input type="submit" value="Post" />
</form>





You can see from the code that the Commentlist component can be divided into a list of comment components. The comment component code is as follows:





<div className="comment">
  <h2 className="commentAuthor">
    {this.props.author}
  </h2>
  <span dangerouslySetInnerHTML= />
</div>





As you can see, in order to complete the comment box function, four different components are defined using react: Commentbox, commentlist, Commentform, comment. Commentbox is a combination of commentlist and commentform, and Commentlist is a combination of comment. This example fully embodies the concept of the react component, where each component's UI and logic are defined internally, exposing a small amount of API and external interaction, and combining components to form more complex components. To summarize, react's components have the following characteristics:


    • Composable: Simple components can be combined into complex components

    • Reusable: Each component is stand-alone and can be used by multiple components

    • Maintainable: Components-related logic and UI are encapsulated inside the component for easy maintenance

    • Testable: Test components are much more convenient because of the component's independence.


React uses a modular design, so developers are naturally compared to native Web Components, and Stackexchange has a great discussion that explains the contrast between react's components and the native component. The article from the language level, the style of encapsulation, data binding, DOM operation and other aspects of the discussion, the conclusion is that the two are not good or bad points, just coding habits problem. After all, the WEB components specification is still in the process of development, should be able to learn from the react component design approach to some ideas. In the following articles, the design principles and use of components in react are discussed in depth.


Virtual DOM


In JavaScript, DOM operations are independent of one branch. Each browser in the implementation of the DOM Operation Library is also similar, all in a separate module to implement the DOM operation, due to various technical reasons, the performance of the DOM operation of the loss relative to other operations is very large. In front-end development, it is necessary to maintain a small number of DOM operations especially to improve performance.



React as a UI framework, it is unavoidable to have interaction of elements on the interface. To improve performance, react introduces the concept of virtual DOM when interacting with pages. The virtual DOM is a DOM model that is re-implemented in react with JavaScript, and does not have much to do with native DOM, but simply draws on some of the concepts of native DOM. The virtual DOM does not fully implement the DOM, but retains the element's direct hierarchical relationship and a small amount of necessary properties. Because the unnecessary complexity is reduced, the result of the practice check is that the performance of the virtual DOM is much higher than the native DOM. Look at the differences in code between the normal DOM and the virtual DOM.



The following elements are generated using the native DOM:





var a = document.createElement(‘a‘)
a.setAttribute(‘class‘, ‘link‘)
a.setAttribute(‘href‘, ‘https://github.com/facebook/react‘)
a.appendChild(document.createTextNode(‘React‘))





Then use the virtual DOM code as follows:





var a = React.createElement(‘a‘, {
    className: ‘link‘,
    href: ‘https://github.com/facebook/react‘
}, ‘React‘)





You can see that the react uses its own implementationcreateElementmethod to generate the element DOM structure.



The DOM built on react development is done through the virtual DOM. In the actual use of react, different UI needs to be presented depending on the data, and when the data changes, react will reconstruct the entire DOM tree, then compare the current DOM tree with the previous comparison to get the difference between the DOM tree, and then simply reflect the changes to the actual browser UI update. React will merge DOM changes within the same event loop, but will compare the DOM changes between the beginning and the end, ignoring the DOM changes in the intermediate process. Although the DOM tree is rebuilt every time the data changes, the virtual DOM has a very high operational performance. When using react, developers do not need to be concerned with updating DOM elements on the page when data changes, but simply care about what the page actually looks like in each data state. In addition, because react uses the virtual DOM implemented by JavaScript, it means that the construction of the HTML structure can be done on the server side.


JSX


JSX is an important part of react, and he uses XML-like notation to declare interfaces and relationships, so he is just a document specification. Here is an example of using JSX inside a react:





var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

React.render(<HelloMessage name="John" />, mountNode);





You can see the code that uses JSX, like a mixture of HTML and JavaScript code. Many people are not accustomed to such coding, and think that this and we have been advocating the performance and logical separation of ideas against, is a kind of retrogression. So what is the purpose of this react design?



React a major design concept is to write code that is simple and easy to understand. The purpose of HTML templates is to separate performance from logic, but in many cases templates are heavily dependent on business logic, and there is no way to completely loose coupling. A slightly more complex example, such as Angularjs, uses a unique set of mechanisms for interacting with the UI and logic, as shown in the example code below.





<ul class="unstyled">
  <li ng-repeat="todo in todoList.todos">
    <input type="checkbox" ng-model="todo.done">
    <span class="done-"></span>
  </li>
</ul>





Using ANGULARJS does show and logically detach from the code perspective, but with a lot of attribute tags in the HTML, these tags are semantically difficult to understand, and novices like to be able to understand the entire logic in a way that is familiar with each of the ng-* corresponding usages and meanings in the angular. So there is a certain threshold for entry. The above example is written using the Jsx method as follows:





render: function () {
  var lis = this.todoList.todos.map(function (todo) {
    return  (
      <li>
        <input type="checkbox" checked={todo.done}>
        <span className="done-{todo.done}">{todo.text}</span>
      </li>);
  });
  return (
    <ul class="unstyled">
      {lis}
    </ul>
  );
}





As you can see, in addition to using HTML tags in jsx, there is no complex markup. This natural and intuitive way directly reduces the react's learning threshold and makes the code easier to understand.



JSX only simplifies the use of react, but it is not necessary. Instead of using JSX in react, you can write code in the same way that native JavaScript is used. The JSX is also converted into JavaScript code to run during the actual use. The React official website provides a tool for online conversion of JSX to native JavaScript code, which can also be used to realize the advantages of JSX and its intrinsic principles.


Flux


Flux is another architecture that is independent of the react. The reason that flux is a schema rather than a framework or a class library is that flux is only used in conjunction with the react framework to handle the interaction between components and data. In simple terms, flux is used to manage data flow. Unlike the bidirectional data binding advocated by other MVC frameworks, Flux uses a one-way data binding mechanism, that is, the flow of data models to views. The following two graphs show the differences between MVC and flux:









There are three main concepts used in flux: Dispatcher, action, and store. These three concepts are different from the MVC model, view, and controller concepts, since MVC is more of a two-way binding of data.



Actions are collections of operations that pass data to dispatcher. The action may be from the user interface, or it may be a server-side data update.



Dispatcher is a global dispatcher that accepts an action and passes it to the registered callback function.



Stores contains the status of the application and the callback functions registered to the dispatcher, which are used to process the business logic.



and React views most closely is store,react view from the store to get state and other data, and update the interface.


Summarize


From the above react related design can be seen, react is to reduce the front-end development of the complexity of the principle. Code written with react is also easy to understand, so it is suitable for large-scale multi-person development, which can improve the project development efficiency and quality.


Reference links
    • React (i): React's philosophy of design-the beauty of simplicity

    • Why did we build React?

    • Facebook React and Web components (polymer) comparative advantages and disadvantages

    • Getting Started with Facebook ' s react.js


Why the react frame is so hot: react's design idea


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.