From 450e5011352a1986c1e72d072b4093f6ef466c6c Mon Sep 17 00:00:00 2001 From: Artem Manukian Date: Sun, 29 Mar 2020 23:06:57 +0300 Subject: [PATCH 01/18] Translate document into Ukrainian --- content/docs/concurrent-mode-patterns.md | 416 +++++++++++------------ 1 file changed, 208 insertions(+), 208 deletions(-) diff --git a/content/docs/concurrent-mode-patterns.md b/content/docs/concurrent-mode-patterns.md index 3f863e497..cec7424b2 100644 --- a/content/docs/concurrent-mode-patterns.md +++ b/content/docs/concurrent-mode-patterns.md @@ -1,6 +1,6 @@ --- id: concurrent-mode-patterns -title: Concurrent UI Patterns (Experimental) +title: Паралельні UI патерни (Експериментальні) permalink: docs/concurrent-mode-patterns.html prev: concurrent-mode-suspense.html next: concurrent-mode-adoption.html @@ -15,63 +15,63 @@ next: concurrent-mode-adoption.html
->Caution: +>Увага: > ->This page describes **experimental features that are [not yet available](/docs/concurrent-mode-adoption.html) in a stable release**. Don't rely on experimental builds of React in production apps. These features may change significantly and without a warning before they become a part of React. +>На сторінці описані **експериментальні функції, [яких ще немає](/docs/concurrent-mode-adoption.html) в стабільній версії**. Не використовуйте експериментальні збірки React в продакшн додатках. Ці функції можуть суттєво змінитися та без попередження потрапити в React. > ->This documentation is aimed at early adopters and people who are curious. **If you're new to React, don't worry about these features** -- you don't need to learn them right now. For example, if you're looking for a data fetching tutorial that works today, read [this article](https://www.robinwieruch.de/react-hooks-fetch-data/) instead. +>Ця документація орієнтована на першопрохідців та зацікавлених користувачів. **Якщо ви новачок в React, не турбуйтеся про ці функції**, немає необхідності вивчати їх прямо зараз. Наприклад, якщо ви шукаєте посібник по вибірці даних, що працює вже зараз, прочитайте [цю статтю](https://www.robinwieruch.de/react-hooks-fetch-data/).
-Usually, when we update the state, we expect to see changes on the screen immediately. This makes sense because we want to keep our app responsive to user input. However, there are cases where we might prefer to **defer an update from appearing on the screen**. - -For example, if we switch from one page to another, and none of the code or data for the next screen has loaded yet, it might be frustrating to immediately see a blank page with a loading indicator. We might prefer to stay longer on the previous screen. Implementing this pattern has historically been difficult in React. Concurrent Mode offers a new set of tools to do that. - -- [Transitions](#transitions) - - [Wrapping setState in a Transition](#wrapping-setstate-in-a-transition) - - [Adding a Pending Indicator](#adding-a-pending-indicator) - - [Reviewing the Changes](#reviewing-the-changes) - - [Where Does the Update Happen?](#where-does-the-update-happen) - - [Transitions Are Everywhere](#transitions-are-everywhere) - - [Baking Transitions Into the Design System](#baking-transitions-into-the-design-system) -- [The Three Steps](#the-three-steps) - - [Default: Receded → Skeleton → Complete](#default-receded-skeleton-complete) - - [Preferred: Pending → Skeleton → Complete](#preferred-pending-skeleton-complete) - - [Wrap Lazy Features in ``](#wrap-lazy-features-in-suspense) - - [Suspense Reveal “Train”](#suspense-reveal-train) - - [Delaying a Pending Indicator](#delaying-a-pending-indicator) - - [Recap](#recap) -- [Other Patterns](#other-patterns) - - [Splitting High and Low Priority State](#splitting-high-and-low-priority-state) - - [Deferring a Value](#deferring-a-value) +Зазвичай, коли ми оновлюємо стан, ми очікуємо негайно побачити зміни на екрані. Це має сенс, тому що ми хочемо щоб наш додаток відкликався на дії користувача. Тим не менше, є випадки, коли нам хотілося б **відкласти оновлення від появи на екрані**. + +Наприклад, якщо ми переходимо з одної сторінки на іншу, і код або дані для наступного екрану досі не завантажились, дивитися спершу на пусту сторінку з індикатором завантаження може бути неприємно. Ми б радше хотіли затриматися на попередньому екрані. Ввести такий патерн в React історично було складно. Паралельний режим пропонує новий набір інструментів для таких цілей. + +- [Переходи](#transitions) + - [Огортання setState в перехід](#wrapping-setstate-in-a-transition) + - [Додавання індикатору очікування](#adding-a-pending-indicator) + - [Перегляд змін](#reviewing-the-changes) + - [Де стається оновлення?](#where-does-the-update-happen) + - [Переходи -- повсюду](#transitions-are-everywhere) + - [Застосування переходів в дизайн-системі](#baking-transitions-into-the-design-system) +- [Три кроки](#the-three-steps) + - [По замовчуванню: Відступ → Кістяк → Завершений](#default-receded-skeleton-complete) + - [Вдосконалений: Очікування → Кістяк → Завершений](#preferred-pending-skeleton-complete) + - [Огорнення ледачих особливостей в ``](#wrap-lazy-features-in-suspense) + - ["Поїзд" з затримок](#suspense-reveal-train) + - [Відкладання індикатору завантаження](#delaying-a-pending-indicator) + - [Підсумок](#recap) +- [Інші патерни](#other-patterns) + - [Розділення високо- та низькоприорітетного стану](#splitting-high-and-low-priority-state) + - [Відстрочка значення](#deferring-a-value) - [SuspenseList](#suspenselist) -- [Next Steps](#next-steps) +- [Наступні кроки](#next-steps) -## Transitions {#transitions} +## Переходи {#transitions} -Let's revisit [this demo](https://codesandbox.io/s/infallible-feather-xjtbu) from the previous page about [Suspense for Data Fetching](/docs/concurrent-mode-suspense.html). +Давайте переглянемо [це демо](https://codesandbox.io/s/infallible-feather-xjtbu) з попередньої сторінки про [Suspense for Data Fetching](/docs/concurrent-mode-suspense.html). -When we click the "Next" button to switch the active profile, the existing page data immediately disappears, and we see the loading indicator for the whole page again. We can call this an "undesirable" loading state. **It would be nice if we could "skip" it and wait for some content to load before transitioning to the new screen.** +При натисканні на кнопку "Next" для зміни активного профілю, існуюча сторінка негайно змикає, а на її місці знову з'являється індикатор завантаження. Ми називаємо це "небажаним" станом завантаження. **Було б чудово мати можливість "пропустити" це і дочекатися, поки контент завантажиться, до переходу на нову сторінку.** -React offers a new built-in `useTransition()` Hook to help with this. +Для таких цілей React пропонує новий вбудований хук `useTransition()`. -We can use it in three steps. +Його можна використати у три троки. -First, we'll make sure that we're actually using Concurrent Mode. We'll talk more about [adopting Concurrent Mode](/docs/concurrent-mode-adoption.html) later, but for now it's sufficient to know that we need to use `ReactDOM.createRoot()` rather than `ReactDOM.render()` for this feature to work: +Спершу, давайте впевнимося, що ми використовуємо Паралельний режим. Більше про [adopting Concurrent Mode](/docs/concurrent-mode-adoption.html) ми поговоримо пізніше, наразі нам достатньо знати, що нам потрібно використовувати `ReactDOM.createRoot()` замість `ReactDOM.render()`, щоб ця властивість запрацювала: ```js const rootElement = document.getElementById("root"); -// Opt into Concurrent Mode +// Використовуємо Паралельний режим ReactDOM.createRoot(rootElement).render(); ``` -Next, we'll add an import for the `useTransition` Hook from React: +Згодом, давайте імпортуємо хук `useTransition` з React: ```js import React, { useState, useTransition, Suspense } from "react"; ``` -Finally, we'll use it inside the `App` component: +Нарешті, давайте застосуємо його в компоненті `App`: ```js{3-5} function App() { @@ -82,18 +82,18 @@ function App() { // ... ``` -**By itself, this code doesn't do anything yet.** We will need to use this Hook's return values to set up our state transition. There are two values returned from `useTransition`: +**Сам по собі, цей код поки що нічого не виконує.** Нам необхідно використати значення, повертаєме даним хуком, щоб налаштувати наші переходи стану. `useTransition` повертає два значення: -* `startTransition` is a function. We'll use it to tell React *which* state update we want to defer. -* `isPending` is a boolean. It's React telling us whether that transition is ongoing at the moment. +* `startTransition`, що є функцією. За допомогою неї ми повідомлятимемо React оновлення *котрого* стану ми хочемо відкласти. +* `isPending`, що є булевим значенням. Цим значенням React повідомляє нас про те, чи наразі відбувається перехід. -We will use them right below. +Ми використаємо його в прикладах нижче. -Note we passed a configuration object to `useTransition`. Its `timeoutMs` property specifies **how long we're willing to wait for the transition to finish**. By passing `{timeoutMs: 3000}`, we say "If the next profile takes more than 3 seconds to load, show the big spinner -- but before that timeout it's okay to keep showing the previous screen". +Зверніть увагу, що ми передаємо об'єкт конфігурації в `useTransition`. Його поле `timeoutMs`, визначає **як довго ми чекатимемо до кінця переходу**. Передавши `{timeoutMs: 3000}`, ми кажемо "якщо наступний профіль завантажиметься довше 3-х секунд, покажи великий спінер -- але допоки час не мине можна відображати попередній екран". -### Wrapping setState in a Transition {#wrapping-setstate-in-a-transition} +### Огортання setState в перехід {#wrapping-setstate-in-a-transition} -Our "Next" button click handler sets the state that switches the current profile in the state: +Обробник події кліку на кнопку "Next" встановлює новий активний профіль у стані: ```js{4}