From 68c2703ccf8aed5ede314d43bff83e229b2130f7 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Mon, 30 Jul 2018 00:43:34 +0300 Subject: [PATCH] chapter1: initial translation --- manuscript/00-foreword/00-introduction.md | 26 +++++++++++------------ 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/manuscript/00-foreword/00-introduction.md b/manuscript/00-foreword/00-introduction.md index b7d6cc4..b170632 100644 --- a/manuscript/00-foreword/00-introduction.md +++ b/manuscript/00-foreword/00-introduction.md @@ -1,25 +1,25 @@ -# Introduction +# Введение -State management in web applications has become a popular topic in the recent years. [Single page applications (SPAs)](https://en.wikipedia.org/wiki/Single-page_application) - that are only delivered once from a web server yet stay interactive on the client - have to establish state management on the client. They have to keep the state consistent in the frontend application without making any more requests to the backend application. They have to give the user an effortless and pleasant experience when using the application. It already starts when opening a popup in your application. It should be possible to open and close it. So someone has to be aware of this state. But who manages this state if it is not the backend application? +Управление состоянием в веб-приложениях стало популярной темой в последние годы. [Одностраничные приложения (SPA)](https://ru.wikipedia.org/wiki/%D0%9E%D0%B4%D0%BD%D0%BE%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%87%D0%BD%D0%BE%D0%B5_%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5) — которые загружаются только один раз с веб-сервера, но остаются интерактивными на клиенте — должны установить управление состоянием на клиенте. Они должны поддерживать согласованность состояния в фронтенд-приложении без каких-либо дополнительных запросов к бекенд-приложению. Они должны дать пользователю легкий и приятный опыт при использовании приложения. Он уже выполняются при открытии всплывающего окна в вашем приложении. Должно быть возможно открыть и закрыть его. Поэтому кто-то должен знать об этом состоянии. Но кто управляет этим состоянием, если это не бекэнд-приложение? -[jQuery](https://en.wikipedia.org/wiki/JQuery) was a popular library before the first SPA solutions, such as Angular, Ember, and Backbone appeared. State management itself wasn't a huge problem in jQuery in the beginning, because the library was most often only used for selective DOM manipulations. You could add animations to your HTML, add or remove DOM nodes or change the style of your HTML programatically. It made web application more enjoyable by making them interactive. +[jQuery](https://ru.wikipedia.org/wiki/JQuery) была популярной библиотекой до появления первых SPA-решений, таких как Angular, Ember и Backbone. Само управление состоянием не было большой проблемой в jQuery в самом начале, потому что эта библиотека чаще всего использовалась только для выборочных манипуляций с DOM. Вы можете добавить анимацию в свой HTML, добавить или удалить DOM-узлы или программно изменить стиль своего HTML. Это сделало веб-приложение более приятным, сделав их интерактивными. -Eventually, the jQuery code, and in general the portion of JavaScript code in contrast to HTML and CSS grew, and people wrote more sophisticated frontend applications. Most of the time, it ended up in a mess of jQuery code where not only state management was a problem, but also general best practices like clean code were missing. There was no solution of a general architecture for these kind of frontend applications and people struggled to keep it maintainable in larger applications. +В конце концов, код jQuery и, в общем, часть кода JavaScript в отличие от HTML и CSS росли, и люди писали более сложные интерфейсные приложения. Большую часть времени он оказался в беспорядке кода jQuery, где проблема не только в управлении состоянием, но и в таких распространённых передовых практиках, таких как чистый код, отсутствовали. Не было решения общей архитектуры для подобных приложений, и люди изо всех сил старались поддерживать его в больших приложениях. -After a while, single page application (SPA) solutions like Angular, Ember and Backbone emerged to give these unstructured frontend applications a proper architectural framework. The greater part of the SPAs build up on the [model-view-controller (MVC) pattern](https://en.wikipedia.org/wiki/Model-view-controller) to architect the application. The mentioned frameworks contain everything you would need, from a view layer for displaying HTML in the browser to a model layer for interacting with your backend, to build your sophisticated application. The term SPA was coined, because these applications are only served once from the web server, as a single page, but then operate only on the client-side. They are blobs of HTML linked to JavaScript which contain everything the applications needs to work on the client-side. When navigating to a different page under a different URL, there is no additional server request required to fetch the HTML with JavaScript. SPAs only interact with the backend to pull or push new data from or to it. Thus, the only thing that changes is the state inside the client-side application, because data is read and written to and from the backend and interactions such as popups, filters and modals have to work. But who manages this state to keep the client-side consistent? +Через некоторое время появились решения для одностраничного приложения (SPA), такие как Angular, Ember и Backbone, чтобы обеспечить эти неструктурированные интерфейсные приложения надлежащей архитектурой. Большая часть SPA формируется на паттерне [model-view-controller (MVC)](https://ru.wikipedia.org/wiki/Model-view-controller) для разработки архитектуры приложения. Указанные фреймворки содержат все, что вам нужно, от уровня представления для отображения HTML в браузере до уровня модели для взаимодействия с вашим бекэндом для создания сложного приложения. Термин SPA был придуман, поскольку эти приложения обслуживаются только один раз с веб-сервера, как одна страница, но затем работают только на стороне клиента. Это капли HTML, связанные с JavaScript, которые содержат все приложения, которые должны работать на стороне клиента. При переходе на другую страницу под другим URL-адресом для получения HTML-кода с использованием JavaScript не требуется дополнительного запроса сервера. SPA взаимодействуют только с бекэндом, чтобы получать или отправлять новые данные из или в него. Таким образом, единственное, что меняется, — это состояние внутри клиентского приложения, поскольку данные считываются и записываются на бекэнд и из него, а взаимодействия, такие как всплывающие окна, фильтры и модальные окна, должно работать. Но кто управляет этим состоянием, чтобы поддерживать целостность на клиентской стороны? -Even though these frameworks for SPAs established best practices, patterns and architectures for the first generation of SPAs, state management became a recurring issue for them. When interacting with the backend to retrieve new data, it was unclear how to manage the data in a predictable way. When triggering view related elements, such as modals or popups, in the frontend, often there wasn't established best practice to manage these states. Every framework tried to apply their own solution for it. Eventually, people came up with their own best practices and libraries, but it never became a predictable and consistent experience to manage state with clear constraints. +Несмотря на то, что эти фреймворки для SPA установили передовые практики, паттерны и архитектуры для первого поколения SPA, управление состоянием стало для них повторяющейся проблемой. При взаимодействии с бекэндом для получения новых данных было непонятно, как управлять данными предсказуемым образом. При запуске представления связанных элементов, таких как модальные окна или всплывающие окна, на фронтенде часто не принято переводой практики для управления этими состояниями. Каждый фреймворк пытается применить к ней собственное решение. В конце концов, люди придумали свои передовые практики и библиотеки, но никогда не стали предсказуемым и последовательным опытом управления состоянием с явными ограничениями. -There was one major flaw with these SPA solutions that led to this problem in the first place: As frameworks, they tried to solve too many issues at once. Because they were the first of their species, they hadn't the chance to solve all issues in the world of SPAs. Eventually, they solved these issues in another iteration when other SPA solutions appeared at the scene. +Был один главный недостаток этих SPA-решений, которые привели к этой проблеме в первую очередь: в качестве фреймворков они пытались решить слишком много проблем одновременно. Поскольку они были первыми из их видов, у них не было возможности решить все проблемы в мире SPA. В конце концов, они решили эти проблемы на другой итерации, когда на сцене появились другие SPA-решения. -The second generation of SPA solutions, among them libraries like React and Vue, focused only on smaller parts of the application. They focused on the view layer. It was up to the engineer to decide on additional libraries as solutions for specific problems. [That's what made React such a powerful library in the first place](https://www.robinwieruch.de/reasons-why-i-moved-from-angular-to-react/), because everyone could decide to extend their application with libraries that solve specific yet small problems. +Второе поколение SPA-решений, среди которых такие библиотеки, как React и Vue, сосредоточено только на небольших частях приложения. Они сосредоточились на уровне представления. Теперь инженерам предстояло выбирать дополнительные библиотеки как решения конкретных проблем. [Это то, что сделало React такой мощной библиотекой в первую очередь](https://www.robinwieruch.de/reasons-why-i-moved-from-angular-to-react/), потому что каждый мог расширить своё приложение с помощью библиотека, которые решают конкретные, но небольшие проблемы. -Nowadays, a ton of articles and libraries try to solve the issue of state management. It is difficult to find a consistent source of truth to learn state management in modern applications. Even though, solutions like React have their own state management implementation for local state in components, there are more external solutions coming as libraries such as Redux and MobX that establish sophisticated state management. +В настоящее время куча статей и библиотек пытается решить проблему управления состоянием. Трудно найти последовательный источник правды для изучения управления состоянием в современных приложениях. Несмотря на то, что такие решения, как React, имеют собственную реализацию управления состоянием для локального состояния в компонентах, для таких библиотек, как Redux и MobX, существуют множество внешних решений, которые создают сложное управление состоянием. -Still, it lacks one guide to navigate through all these different solutions to make the differences and benefits of state management clear. Quite often, the guides miss the point of teaching the problem first. In addition, instead of showing the minimal approach, they try to fix the problem of state management by using over-engineered approaches. But it can be so much simpler. It only needs one resource to guide through state management in modern applications in a consistent and constructive way. And that's the mission of this book. +Тем не менее, ему не хватает одного руководства для навигации по всем этим различным решениям, чтобы выявить различия и преимущества управления состоянием ясными. Довольно часто руководства упускают из виду проблему сути обучения в первую очередь. Кроме того, вместо того, чтобы показывать минимальный подход, они пытаются решить проблему управления состоянием, используя чрезмерно переусложненные подходы. Но это может быть намного проще. Нужен только один ресурс, который будет указывать путь к последовательному и конструктивному управлению состоянием в современных приложениях. И это миссия этой книги. -If you want to learn something, you have to do it step by step. Trying to solve each atomic problem after the next one. Don't apply everything at once. Understand the problem and solve it. That's my attempt with this book: It doesn't only teach Redux in React, but state management in modern applications. It goes beyond the documentation of state management libraries, but applies the learnings in real world applications in the book. +Если вы хотите чему-то научиться, вам нужно делать это шаг за шагом. Пытаться решить любую элементарную проблему перед следующей. Не применяйте все сразу. Поймите проблему и решите ее. Это моя попытка с этой книгой: она не только преподает Redux в React, но и управление состоянием в современных приложениях. Она выходит за рамки документации библиотек управления состоянием, но и применяет знания в реальных приложениях в книге. -The book follows the central theme of state management in modern applications. It starts with local state management in a view library (React), points out the problems of it in larger applications and will lead over to sophisticated state management solutions such as Redux and MobX. While you read the book, you will find code playgrounds that illustrate problems and solutions. I encourage you to play around with these code playgrounds to have a practical experience. You can even try to apply these code snippets in your personal editor and play around with them. But don't worry if it doesn't work out in the beginning. You will be guided by me to apply your learnings in your editor in various chapters. However, don't hesitate to verify your learnings early on. +Книга следует центральной теме управления состоянием в современных приложениях. Она начинается с управления локальным состоянием в библиотеке представления (React), указывает на проблемы её использования в более крупных приложениях и приводит к сложным решениям управления состоянием, таким как Redux и MobX. Пока вы читаете книгу, вы найдете интерактивные площадки для выполнения кода, которые иллюстрируют проблемы и решения. Я рекомендую вам поиграть с этими площадками, чтобы получить практический опыт. Вы даже можете попытаться применить эти фрагменты кода в своем личном редакторе и поиграть с ними. Но не беспокойтесь, если это не сработает в начале. Вы будете руководствоваться мною, чтобы применить свои знания в своем редакторе в разных главах. Однако, не стесняйтесь проверять свои знания как можно раньше. -These are the heroes of the book: Local State (in React), Redux and MobX. It wouldn't have been possible to write the book without the innovators behind these solutions: [Dan Abramov](https://twitter.com/dan_abramov), [Andrew Clark](https://twitter.com/acdlite) and [Michel Weststrate](https://twitter.com/mweststrate). I guess, I can thank them in the name of the community for their efforts to make state management in modern applications a consistent and enjoyable experience. \ No newline at end of file +Это герои книги: локальное состояние (в React), Redux и MobX. Было бы невозможно написать книгу без новаторов, стоящих за этими решениями: [Дэн Абрамов](https://twitter.com/dan_abramov), [Andrew Clark](https://twitter.com/acdlite) и [Michel Weststrate](https://twitter.com/mweststrate). Наверное, я могу поблагодарить их от имени сообщества за их усилия сделать управление состоянием в современных приложениях последовательным и приятным опытом. \ No newline at end of file