Home > Web Front-end > JS Tutorial > 2018 js review: The fundamental reasons for the existence of the framework are these

2018 js review: The fundamental reasons for the existence of the framework are these

php是最好的语言
Release: 2018-07-25 09:53:19
Original
965 people have browsed it

The main problem solved by modern js frameworks is keeping the UI and state in sync. Writing complex, efficient, and maintainable UI interfaces using native JavaScript is nearly impossible. I have seen many, many people blindly use (front-end) frameworks such as React, Angular or Vue, etc. These frameworks provide a lot of interesting stuff, but usually people (think) use frameworks because:

  • They support componentization;

  • They have strong community support;

  • They have many (framework-based) third-party libraries to solve Problem;

  • They have a lot of (good) third party components;

  • They have browser extensions to help with debugging;

  • They are suitable for single-page applications.

But these are not the fundamental reasons for using the framework.

The most essential reason is:

2018 js review: The fundamental reasons for the existence of the framework are these

(It is very difficult to synchronize UI and state)

Yes, that’s it Reasons, let's take a look at why

Suppose you are designing a web application where users can invite others (to participate in an event) by sending a group email. The UX/UI designer designed it as follows: (before the user fills in any email address,) there is a blank state and adds some help information for this; (after the user fills in the email address,) the email address is displayed on the right side of each address There is a button for deleting the corresponding address.

2018 js review: The fundamental reasons for the existence of the framework are these

The status of this form can be designed as an array, which contains several objects. The objects consist of email addresses and unique identifiers. At the beginning, the array is empty. After (the user) enters their email address and presses Enter, add an item to the array and update the UI. When the user clicks the delete button, delete the email address (corresponding to the array) and update the UI. Did you feel it? Every time you change state, you need to update the UI.

(You might say:) So what? Well, let’s see how to implement it without a framework:

Implementing a relatively complex UI using native (JS)

The following code nicely illustrates the implementation using native JavaScript The amount of work required for a relatively complex UI is similar to the amount of work required to use a classic library like jQuery.

In this example, HTML is responsible for creating static pages, and JavaScript dynamically changes (DOM structure) through <span class="pln" style="color:rgb(72,72,76);">document</span><span class="pun" style="color:rgb(147,161,161);">.</span><span class="pln" style="color:rgb(72,72,76);">createElement</span>. This leads to the first problem: the JavaScript code related to building UI is not intuitive and easy to read. We divide UI building into two parts (Translator's Note: It should refer to HTML and JavaScript parts). Although we use <span class="pln" style="color:rgb(72,72,76);">innerHTML</span>, readability is enhanced, but performance (of the page) is reduced, and CSRF vulnerabilities may exist. We can also use a template engine, but if we modify the DOM in a large area, we will face two problems: low efficiency and the need to rebind the event handler.

But this is not the biggest problem (without using a framework). The biggest problem is having to (manually) update the UI every time the state changes. This requires a lot of code to change the UI every time the status is updated. When adding an email address, it only takes two lines of code to update the status, but thirteen lines of code to update the UI. (In this case) We've made the UI (interface and logic) as simple as possible! !

2018 js review: The fundamental reasons for the existence of the framework are these

The code is difficult to write and difficult to understand. What's even more troublesome is that it is very fragile. Suppose we need (add) the function of synchronizing server data to a list of email addresses, and we need to compare the difference between the results returned by the server and the data in the array. This involves comparing the identity and content of all data, which may require retaining a copy of data with the same identity but different content in memory (when modified by the user).

In order to change the DOM efficiently, we need to write a lot of point-to-point (Translator's Note: refers to state to UI) code. ButAs soon as you make a small mistake, the UI and state will no longer be in sync: (possibly) missing or wrong information, no longer responding to user operations, or worse, triggering The wrong action was taken (such as clicking the delete button and then deleting a non-corresponding item).

So keeping the UI in sync with the state requires writing a lot of tedious and very brittle code.

Responsive UI saves everything

2018 js review: The fundamental reasons for the existence of the framework are these

So, (the reason for using the framework is) not because of the community, not because of the tools, not because of the ecology, not because of the third Third-party libraries...

So far, the biggest improvement of the framework is that it provides (for us) a reliable guarantee of synchronization between the internal state of the application and the UI.

As long as you know some (specific) rules of a specific framework (such as immutable state), it's almost (can be used normally).

We only need to define the UI interface once, and no longer need to write specific UI code for each operation. At the same time, each same state has the same output (Translator's Note: Refers to UI consistency): When the state changes, the framework automatically updates the (corresponding) view.

How does the framework work?

Based on two basic strategies:

  • Re-render the entire component, like React. When the state in a component changes, the (new) DOM structure is calculated in memory and compared with the existing DOM structure. In fact, it's very expensive. Therefore, the real DOM is mapped to the virtual DOM, and by comparing the differences between the virtual DOM before and after the state change, the changes are calculated and then the real DOM structure is changed. This process is called reconciliation.

  • #Monitor changes via (added) observers like Angular and Vue.js. The properties of the application state are monitored, and when they change, only the DOM elements that depend on the (changed) properties are re-rendered.

What about Web components?

Many times, people compare React, Angular and Vue.js (frameworks such as) with Web components. This clearly shows that people don't understand the biggest benefit these frameworks provide: keeping the UI in sync with the state. Web components do not provide this synchronization mechanism. Itonlyprovides a template tag, but it does not provide any coordination mechanism (between state and UI). If you want to keep the UI synchronized with the internal state when using Web components in your application, you need to do it manually (developer), or use something like Stencil.js (Internally the same as React , using libraries like Virtual DOM).

Let us be clear: the huge potential of the framework is not reflected in componentization, but in keeping the UI and state synchronized. Web components do not provide related functionality, you must solve the (synchronization) problem manually or use a third-party library. It's basically impossible to write complex, efficient, and easy-to-maintain UI interfaces using native JavaScript. This is the fundamental reason why you need to use a modern JavaScript framework.

Do it yourself and have enough food and clothing

If you are keen on understanding the underlying principles, you would like to know the specific implementation of virtual DOM. So, why not try to rewrite the native UI using only virtual DOM without using a framework?

This is the core of the framework, the base class for all components.

2018 js review: The fundamental reasons for the existence of the framework are these

Here is the rewritten AddressList component (using babel to support JSX conversion).

2018 js review: The fundamental reasons for the existence of the framework are these

Теперь пользовательский интерфейс является декларативным и мы не используем никакой фреймворк. Мы можем добавить новую логику для изменения состояния по своему желанию без написания дополнительного кода для синхронизации пользовательского интерфейса. Проблема решена!

За исключением обработки событий, это похоже на приложение React, верно? У нас есть <span class="pln" style="color:rgb(72,72,76);">haverender</span><span class="pun" style="color:rgb(147,161,161);">()</span>, <span class="pln" style="color:rgb(72,72,76);">comComponentDidMount</span><span class="pun" style="color:rgb(147,161,161);">()</span>, <span class="pln" style="color:rgb(72,72,76);">setState</span><span class="pun" style="color:rgb(147,161,161);">()</span> и так далее. Как только вы решите проблему синхронизации пользовательского интерфейса и состояния внутри приложения, все естественным образом сложится (компоненты формы).

Полный исходный код можно найти в этом репозитории Github.

Заключение

  • Основная проблема, которую решают современные js-фреймворки, — это синхронизация пользовательского интерфейса с состоянием.

Написание сложных, эффективных и удобных в обслуживании интерфейсов пользовательского интерфейса с использованием встроенного JavaScript практически невозможно.

#Веб-компоненты не решают проблемы синхронизации.

Не сложно использовать существующую виртуальную библиотеку DOM для создания собственной структуры. Но это не рекомендуется!

#########Рекомендации по теме: ######### Причины и решения невозможности загрузки файлов css и js в php ci framework####### # ####Видео: 27 классических практических видеоуроков по интерфейсной JS-разработке############Видео: видеоурок по расширенному дизайну инфраструктуры JavaScript без онлайн-видеоуроков####### ### #####

The above is the detailed content of 2018 js review: The fundamental reasons for the existence of the framework are these. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template