diff --git a/content/docs/concurrent-mode-reference.md b/content/docs/concurrent-mode-reference.md index bfc06e731..58f593acd 100644 --- a/content/docs/concurrent-mode-reference.md +++ b/content/docs/concurrent-mode-reference.md @@ -1,6 +1,6 @@ --- id: concurrent-mode-reference -title: Concurrent Mode API Reference (Experimental) +title: Справочник API конкурентного режима (экспериментально) permalink: docs/concurrent-mode-reference.html prev: concurrent-mode-adoption.html --- @@ -14,28 +14,28 @@ prev: 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. +>На странице описаны **экспериментальные функции, которых еще нет в стабильной версии**. Не используйте экспериментальные сборки 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. +>Эта документация предназначена для ранних пользователей и интересующихся. Если вы новичок в React, не беспокойтесь об этих возможностях -- вам не нужно изучать их прямо сейчас.
-This page is an API reference for the React [Concurrent Mode](/docs/concurrent-mode-intro.html). If you're looking for a guided introduction instead, check out [Concurrent UI Patterns](/docs/concurrent-mode-patterns.html). +Страница содержит справочник API [конкурентного режима](/docs/concurrent-mode-intro.html) React. Если вам нужно вводное руководство по этому режиму, прочитайте о [паттернах конкурентного UI](/docs/concurrent-mode-patterns.html). -**Note: This is a Community Preview and not the final stable version. There will likely be future changes to these APIs. Use at your own risk!** +**Примечание: это не стабильный релиз, а предварительная версия для сообщества. Скорее всего, в будущем API изменится. Используйте его на свой страх и риск!** -- [Enabling Concurrent Mode](#concurrent-mode) +- [Включение конкурентного режима](#concurrent-mode) - [`createRoot`](#createroot) - [`createBlockingRoot`](#createblockingroot) -- [Suspense](#suspense) +- [API задержек](#suspense) - [`Suspense`](#suspensecomponent) - [`SuspenseList`](#suspenselist) - [`useTransition`](#usetransition) - [`useDeferredValue`](#usedeferredvalue) -## Enabling Concurrent Mode {#concurrent-mode} +## Включение конкурентного режима {#concurrent-mode} ### `createRoot` {#createroot} @@ -43,9 +43,9 @@ This page is an API reference for the React [Concurrent Mode](/docs/concurrent-m ReactDOM.createRoot(rootNode).render(); ``` -Replaces `ReactDOM.render(, rootNode)` and enables Concurrent Mode. +Заменяет `ReactDOM.render(, rootNode)` и включает конкурентный режим. -For more information on Concurrent Mode, check out the [Concurrent Mode documentation.](/docs/concurrent-mode-intro.html) +Дополнительную информацию можно узнать в [документации конкурентного режима](/docs/concurrent-mode-intro.html). ### `createBlockingRoot` {#createblockingroot} @@ -53,61 +53,61 @@ For more information on Concurrent Mode, check out the [Concurrent Mode document ReactDOM.createBlockingRoot(rootNode).render() ``` -Replaces `ReactDOM.render(, rootNode)` and enables [Blocking Mode](/docs/concurrent-mode-adoption.html#migration-step-blocking-mode). +Заменяет `ReactDOM.render(, rootNode)` и включает [блокирующий режим](/docs/concurrent-mode-adoption.html#migration-step-blocking-mode). -Opting into Concurrent Mode introduces semantic changes to how React works. This means that you can't use Concurrent Mode in just a few components. Because of this, some apps may not be able to migrate directly to Concurrent Mode. +Для реализации конкурентного режима решено сделать семантические изменения в работе React. Это значит, что вы не сможете использовать конкурентный режим лишь для некоторых компонентов проекта. И как следствие, не все приложения можно будет напрямую перевести на конкурентный режим. -Blocking Mode only contains a small subset of Concurrent Mode features and is intended as an intermediary migration step for apps that are unable to migrate directly. +Блокирующий режим содержит небольшую часть возможностей конкурентного режима. Он предназначен в качестве промежуточного этапа для приложений, которые нельзя мигрировать напрямую. -## Suspense API {#suspense} +## API задержек {#suspense} ### `Suspense` {#suspensecomponent} ```js -Loading...}> +Загрузка...}> ``` -`Suspense` lets your components "wait" for something before they can render, showing a fallback while waiting. +`Suspense` позволяет вашим компонентам "ждать", отображая запасной интерфейс, прежде чем они будут отрендерены. -In this example, `ProfileDetails` is waiting for an asynchronous API call to fetch some data. While we wait for `ProfileDetails` and `ProfilePhoto`, we will show the `Loading...` fallback instead. It is important to note that until all children inside `` has loaded, we will continue to show the fallback. +В примере компонент `ProfileDetails` получает данные с помощью асинхронного вызова. Во время ожидания загрузки `ProfileDetails` и `ProfilePhoto`, отображается запасной заголовок `Загрузка...`. Следует отметить, что до тех пор, пока все дочерние компоненты `` не отрендерены, мы увидим запасной интерфейс. -`Suspense` takes two props: -* **fallback** takes a loading indicator. The fallback is shown until all of the children of the `Suspense` component have finished rendering. -* **unstable_avoidThisFallback** takes a boolean. It tells React whether to "skip" revealing this boundary during the initial load. This API will likely be removed in a future release. +`Suspense` принимает два пропса: +* **fallback** принимает индикатор загрузки. Запасной интерфейс отображается до тех пор, пока не завершится рендер всех дочерних компонентов `Suspense`. +* **unstable_avoidThisFallback** принимает логическое значение. Оно сообщает React, что не нужно отображать запасной интерфейс при первоначальной загрузке. Скорее всего, этот API будет исключён в будущих релизах. ### `` {#suspenselist} ```js - + - + - + ... ``` -`SuspenseList` helps coordinate many components that can suspend by orchestrating the order in which these components are revealed to the user. +`SuspenseList` помогает скоординировать загрузку множества компонентов с помощью определения порядка, в котором они будут показываться пользователю. -When multiple components need to fetch data, this data may arrive in an unpredictable order. However, if you wrap these items in a `SuspenseList`, React will not show an item in the list until previous items have been displayed (this behavior is adjustable). +Бывают ситуации, когда нескольким компонентам требуется получить данные, последовательность загрузки которых нельзя предсказать заранее. Если обернуть такие компоненты в `SuspenseList`, то React не покажет компонент из списка до тех пор, пока не будет отображён предыдущий (этим поведением можно управлять). -`SuspenseList` takes two props: -* **revealOrder (forwards, backwards, together)** defines the order in which the `SuspenseList` children should be revealed. - * `together` reveals *all* of them when they're ready instead of one by one. -* **tail (collapsed, hidden)** dictates how unloaded items in a `SuspenseList` is shown. - * By default, `SuspenseList` will show all fallbacks in the list. - * `collapsed` shows only the next fallback in the list. - * `hidden` doesn't show any unloaded items. +`SuspenseList` принимает два пропса: +* **revealOrder (forwards, backwards, together)** определяет последовательность, в которой отображаются дочерние компоненты `SuspenseList`. + * `together` позволяет отобразить *все* компоненты одновременно вместо того, чтобы показывать их последовательно. +* **tail (collapsed, hidden)** определяет, как отображаются компоненты из `SuspenseList`, которые ещё не загружены. + * По умолчанию `SuspenseList` отображает запасной интерфейс для всех компонентов в списке. + * `collapsed` показывает запасной интерфейс только для компонента, который будет загружен следующим. + * `hidden` не показывает компоненты, которые ещё не загружены. -Note that `SuspenseList` only operates on the closest `Suspense` and `SuspenseList` components below it. It does not search for boundaries deeper than one level. However, it is possible to nest multiple `SuspenseList` components in each other to build grids. +Учтите, что `SuspenseList` управляет только ближайшими вложенными компонентами `Suspense` и `SuspenseList`. Поиск осуществляется не более, чем на один уровень вниз, но при этом можно делать многоуровневые вложения `SuspenseList` для построения более сложной разметки. ### `useTransition` {#usetransition} @@ -117,13 +117,13 @@ const SUSPENSE_CONFIG = { timeoutMs: 2000 }; const [startTransition, isPending] = useTransition(SUSPENSE_CONFIG); ``` -`useTransition` allows components to avoid undesirable loading states by waiting for content to load before **transitioning to the next screen**. It also allows components to defer slower, data fetching updates until subsequent renders so that more crucial updates can be rendered immediately. +`useTransition` позволяет не отображать состояние загрузки, когда контент обновляется перед **переходом к следующему экрану**. Это также позволяет компонентам так откладывать более медленные обновления выборки данных до последующих рендеров, что более важные обновления могут быть выполнены немедленно. -The `useTransition` hook returns two values in an array. -* `startTransition` is a function that takes a callback. We can use it to tell React which state we want to defer. -* `isPending` is a boolean. It's React's way of informing us whether we're waiting for the transition to finish. +Хук `useTransition` возвращает массив из двух элементов. +* `startTransition` -- это функция, которая получает колбэк. Её используют, чтобы сообщить React, какое состояние нам нужно отложить. +* `isPending` -- это логическое значение, которое позволяет React проинформировать нас, ожидаем ли мы в данный момент окончания перехода. -**If some state update causes a component to suspend, that state update should be wrapped in a transition.** +**Если обновление состояния компонента является причиной задержки, то его нужно обернуть по паттерну перехода.** ```js const SUSPENSE_CONFIG = { timeoutMs: 2000 }; @@ -144,7 +144,7 @@ function App() { > Next - {isPending ? " Loading..." : null} + {isPending ? " Загрузка..." : null} }> @@ -153,21 +153,21 @@ function App() { } ``` -In this code, we've wrapped our data fetching with `startTransition`. This allows us to start fetching the profile data right away, while deferring the render of the next profile page and its associated `Spinner` for 2 seconds (the time shown in `timeoutMs`). +В этом примере мы обернули получение данных в функцию `startTransition`. Это позволяет сразу загружать данные профиля пользователя, откладывая рендер страницы и компонента `Spinner` на 2 секунды (время указано в `timeoutMs`). -The `isPending` boolean lets React know that our component is transitioning, so we are able to let the user know this by showing some loading text on the previous profile page. +Логическое значение `isPending` показывает, что наш компонент в состоянии перехода. Это позволяет, находясь на предыдущем экране, показать пользователю сообщение о загрузке. -**For an in-depth look at transitions, you can read [Concurrent UI Patterns](/docs/concurrent-mode-patterns.html#transitions).** +**Паттерн перехода более подробно рассматривается в разделе [Паттерны конкурентного UI](/docs/concurrent-mode-patterns.html#transitions).** -#### useTransition Config {#usetransition-config} +#### Конфигурирование useTransition {#usetransition-config} ```js const SUSPENSE_CONFIG = { timeoutMs: 2000 }; ``` -`useTransition` accepts an **optional Suspense Config** with a `timeoutMs`. This timeout (in milliseconds) tells React how long to wait before showing the next state (the new Profile Page in the above example). +Хук `useTransition` принимает **объект настройки задержек** со свойством `timeoutMs`. Этот тайм-аут, заданный в миллисекундах, указывает React, сколько времени нужно ждать появления следующего состояния, например, как это было сделано в программе выше. -**Note: We recommend that you share Suspense Config between different modules.** +**Примечание: мы рекомендуем делать объект настройки задержек глобальным для всех модулей проекта.** ### `useDeferredValue` {#usedeferredvalue} @@ -176,39 +176,39 @@ const SUSPENSE_CONFIG = { timeoutMs: 2000 }; const deferredValue = useDeferredValue(value, { timeoutMs: 2000 }); ``` -Returns a deferred version of the value that may "lag behind" it for at most `timeoutMs`. +Хук возвращает отложенную версию для значения, получение которого может «отставать» от рендера всего компонента более чем на `timeoutMs`. -This is commonly used to keep the interface responsive when you have something that renders immediately based on user input and something that needs to wait for a data fetch. +Обычно этот хук используется для создания отзывчивого интерфейса, когда часть компонента нужно немедленно отрендерить на основе пользовательского ввода и при этом другая часть ожидает загрузки данных. -A good example of this is a text input. +Хорошим примером является ввод текста. ```js function App() { const [text, setText] = useState("hello"); - const deferredText = useDeferredValue(text, { timeoutMs: 2000 }); + const deferredText = useDeferredValue(text, { timeoutMs: 2000 }); return (
- {/* Keep passing the current text to the input */} + {/* Вводим текст в поле ... */} ... - {/* But the list is allowed to "lag behind" when necessary */} + {/* ... при этом список может отображать отложенное значение */}
); } ``` -This allows us to start showing the new text for the `input` immediately, which allows the webpage to feel responsive. Meanwhile, `MySlowList` "lag behind" for up to 2 seconds according to the `timeoutMs` before updating, allowing it to render with the current text in the background. +Такой подход позволяет немедленно показывать новый текст для `input`, чтобы улучшить отзывчивость UI. В тоже время, если рендер `MySlowList` "отстает" на 2 секунды, установленные в `timeoutMs`, то в фоновом режиме отображается отложенное значение. -**For an in-depth look at deferring values, you can read [Concurrent UI Patterns](/docs/concurrent-mode-patterns.html#deferring-a-value).** +**Паттерн ожидания значений более подробно рассматривается в разделе [Паттерны конкурентного UI](/docs/concurrent-mode-patterns.html#deferring-a-value).** -#### useDeferredValue Config {#usedeferredvalue-config} +#### Конфигурирование useDeferredValue {#usedeferredvalue-config} ```js const SUSPENSE_CONFIG = { timeoutMs: 2000 }; ``` -`useDeferredValue` accepts an **optional Suspense Config** with a `timeoutMs`. This timeout (in milliseconds) tells React how long the deferred value is allowed to lag behind. +`useDeferredValue` принимает **объект настройки задержек** со свойством `timeoutMs`. Этот тайм-аут (в миллисекундах) сообщает React, на сколько долго отложенное значение может отставать. -React will always try to use a shorter lag when network and device allows it. +React будет пытаться использовать более короткую задержку, когда сеть и устройство это позволяют. diff --git a/content/docs/nav.yml b/content/docs/nav.yml index ee335fe48..cac9a5601 100644 --- a/content/docs/nav.yml +++ b/content/docs/nav.yml @@ -147,7 +147,7 @@ - id: concurrent-mode-adoption title: Использование конкурентного режима - id: concurrent-mode-reference - title: Concurrent Mode API Reference + title: Справочник API конкурентного режима - title: Участие в проекте items: - id: how-to-contribute