diff --git a/src/content/reference/react-dom/client/hydrateRoot.md b/src/content/reference/react-dom/client/hydrateRoot.md index b74e2c38ee..4202227192 100644 --- a/src/content/reference/react-dom/client/hydrateRoot.md +++ b/src/content/reference/react-dom/client/hydrateRoot.md @@ -1,10 +1,9 @@ --- title: hydrateRoot --- - -`hydrateRoot` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](/reference/react-dom/server) +`hydrateRoot` позволяет отображать компоненты React внутри узла DOM браузера, HTML-содержимое которого было ранее сгенерировано [`react-dom/server`.](/reference/react-dom/server) ```js const root = hydrateRoot(domNode, reactNode, options?) @@ -16,11 +15,11 @@ const root = hydrateRoot(domNode, reactNode, options?) --- -## Reference {/*reference*/} +## Справочник {/*reference*/} ### `hydrateRoot(domNode, reactNode, options?)` {/*hydrateroot*/} -Call `hydrateRoot` to “attach” React to existing HTML that was already rendered by React in a server environment. +Вызовите `hydrateRoot`, чтобы «прикрепить» React к существующему HTML, который уже был отрисован React на сервере. ```js import { hydrateRoot } from 'react-dom/client'; @@ -29,101 +28,101 @@ const domNode = document.getElementById('root'); const root = hydrateRoot(domNode, reactNode); ``` -React will attach to the HTML that exists inside the `domNode`, and take over managing the DOM inside it. An app fully built with React will usually only have one `hydrateRoot` call with its root component. +React прикрепится к HTML, который существует внутри `domNode`, и возьмёт на себя управление DOM внутри него. Приложение, полностью построенное с использованием React, обычно будет иметь только один вызов `hydrateRoot` с его корневым компонентом. -[See more examples below.](#usage) +[См. больше примеров ниже.](#usage) -#### Parameters {/*parameters*/} +#### Параметры {/*parameters*/} -* `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that was rendered as the root element on the server. +* `domNode`: [DOM-элемент](https://developer.mozilla.org/en-US/docs/Web/API/Element), который был отрисован как корневой элемент на сервере. -* `reactNode`: The "React node" used to render the existing HTML. This will usually be a piece of JSX like `` which was rendered with a `ReactDOM Server` method such as `renderToPipeableStream()`. +* `reactNode`: «React-узел», использованный для отрисовки существующего HTML. Обычно это фрагмент JSX, такой как ``, который был отрисован с помощью метода `ReactDOM Server`, например `renderToPipeableStream()`. -* **optional** `options`: An object with options for this React root. +* **необязательный** `options`: Объект с параметрами для этого корневого узла React. - * **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary. Called with the `error` caught by the Error Boundary, and an `errorInfo` object containing the `componentStack`. - * **optional** `onUncaughtError`: Callback called when an error is thrown and not caught by an Error Boundary. Called with the `error` that was thrown and an `errorInfo` object containing the `componentStack`. - * **optional** `onRecoverableError`: Callback called when React automatically recovers from errors. Called with the `error` React throws, and an `errorInfo` object containing the `componentStack`. Some recoverable errors may include the original error cause as `error.cause`. - * **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server. + * **необязательный** `onCaughtError`: Функция обратного вызова, вызываемая, когда React перехватывает ошибку в Error Boundary. Вызывается с ошибкой `error`, перехваченной Error Boundary, и объектом `errorInfo`, содержащим `componentStack`. + * **необязательный** `onUncaughtError`: Функция обратного вызова, вызываемая, когда выбрасывается ошибка, не перехваченная Error Boundary. Вызывается с ошибкой `error`, которая была выброшена, и объектом `errorInfo`, содержащим `componentStack`. + * **необязательный** `onRecoverableError`: Функция обратного вызова, вызываемая, когда React автоматически восстанавливается после ошибок. Вызывается с ошибкой `error`, которую выбрасывает React, и объектом `errorInfo`, содержащим `componentStack`. Некоторые восстанавливаемые ошибки могут включать исходную причину ошибки как `error.cause`. + * **необязательный** `identifierPrefix`: Строковый префикс, который React использует для идентификаторов, сгенерированных [`useId`.](/reference/react/useId) Полезен для предотвращения конфликтов при использовании нескольких корневых узлов на одной странице. Должен быть тем же префиксом, что и использованный на сервере. -#### Returns {/*returns*/} +#### Возвращает {/*returns*/} -`hydrateRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount) +`hydrateRoot` возвращает объект с двумя методами: [`render`](#root-render) и [`unmount`.](#root-unmount) -#### Caveats {/*caveats*/} +#### Ограничения {/*caveats*/} -* `hydrateRoot()` expects the rendered content to be identical with the server-rendered content. You should treat mismatches as bugs and fix them. -* In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive. -* You'll likely have only one `hydrateRoot` call in your app. If you use a framework, it might do this call for you. -* If your app is client-rendered with no HTML rendered already, using `hydrateRoot()` is not supported. Use [`createRoot()`](/reference/react-dom/client/createRoot) instead. +* `hydrateRoot()` ожидает, что отрисованное содержимое будет идентично содержимому, отрисованному на сервере. Расхождения следует рассматривать как ошибки и исправлять их. +* В режиме разработки React предупреждает о расхождениях во время гидратации. Нет никаких гарантий, что различия в атрибутах будут исправлены в случае расхождений. Это важно по соображениям производительности, поскольку в большинстве приложений расхождения редки, и проверка всего разметки была бы непомерно дорогой. +* Вероятно, в вашем приложении будет только один вызов `hydrateRoot`. Если вы используете фреймворк, он может выполнить этот вызов за вас. +* Если ваше приложение отрисовывается на клиенте без предварительно отрисованного HTML, использование `hydrateRoot()` не поддерживается. Вместо этого используйте [`createRoot()`](/reference/react-dom/client/createRoot). --- ### `root.render(reactNode)` {/*root-render*/} -Call `root.render` to update a React component inside a hydrated React root for a browser DOM element. +Вызовите `root.render`, чтобы обновить компонент React внутри гидрированного корневого узла React для браузерного DOM-элемента. ```js root.render(); ``` -React will update `` in the hydrated `root`. +React обновит `` в гидрированном `root`. -[See more examples below.](#usage) +[См. больше примеров ниже.](#usage) -#### Parameters {/*root-render-parameters*/} +#### Параметры {/*root-render-parameters*/} -* `reactNode`: A "React node" that you want to update. This will usually be a piece of JSX like ``, but you can also pass a React element constructed with [`createElement()`](/reference/react/createElement), a string, a number, `null`, or `undefined`. +* `reactNode`: «React-узел», который вы хотите обновить. Обычно это фрагмент JSX, такой как ``, но вы также можете передать React-элемент, созданный с помощью [`createElement()`](/reference/react/createElement), строку, число, `null` или `undefined`. -#### Returns {/*root-render-returns*/} +#### Возвращает {/*root-render-returns*/} -`root.render` returns `undefined`. +`root.render` возвращает `undefined`. -#### Caveats {/*root-render-caveats*/} +#### Ограничения {/*root-render-caveats*/} -* If you call `root.render` before the root has finished hydrating, React will clear the existing server-rendered HTML content and switch the entire root to client rendering. +* Если вы вызовете `root.render` до того, как корневой узел закончит гидратацию, React очистит существующее содержимое HTML, отрисованное на сервере, и переключит весь корневой узел на рендеринг на клиенте. --- ### `root.unmount()` {/*root-unmount*/} -Call `root.unmount` to destroy a rendered tree inside a React root. +Вызовите `root.unmount`, чтобы уничтожить отрисованное дерево внутри корневого узла React. ```js root.unmount(); ``` -An app fully built with React will usually not have any calls to `root.unmount`. +Приложение, полностью построенное с использованием React, обычно не будет иметь вызовов `root.unmount`. -This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. You need to tell React to "stop" managing the removed root's content by calling `root.unmount`. Otherwise, the components inside the removed root won't clean up and free up resources like subscriptions. +Это в основном полезно, если DOM-узел вашего корневого узла React (или любой из его предков) может быть удален из DOM каким-либо другим кодом. Например, представьте себе панель вкладок jQuery, которая удаляет неактивные вкладки из DOM. Если вкладка удаляется, все внутри нее (включая корневые узлы React) также будет удалено из DOM. Вам нужно сообщить React, чтобы он «прекратил» управление содержимым удаленного корневого узла, вызвав `root.unmount`. В противном случае компоненты внутри удаленного корневого узла не будут очищены и не освободят ресурсы, такие как подписки. -Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree. +Вызов `root.unmount` размонтирует все компоненты в корневом узле и «отсоединит» React от корневого DOM-узла, включая удаление любых обработчиков событий или состояния в дереве. -#### Parameters {/*root-unmount-parameters*/} +#### Параметры {/*root-unmount-parameters*/} -`root.unmount` does not accept any parameters. +`root.unmount` не принимает никаких параметров. -#### Returns {/*root-unmount-returns*/} +#### Возвращает {/*root-unmount-returns*/} -`root.unmount` returns `undefined`. +`root.unmount` возвращает `undefined`. -#### Caveats {/*root-unmount-caveats*/} +#### Ограничения {/*root-unmount-caveats*/} -* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node. +* Вызов `root.unmount` размонтирует все компоненты в дереве и «отсоединит» React от корневого DOM-узла. -* Once you call `root.unmount` you cannot call `root.render` again on the root. Attempting to call `root.render` on an unmounted root will throw a "Cannot update an unmounted root" error. +* После вызова `root.unmount` вы больше не сможете вызывать `root.render` для этого корневого узла. Попытка вызвать `root.render` для размонтированного корневого узла приведет к ошибке "Cannot update an unmounted root". --- -## Usage {/*usage*/} +## Использование {/*usage*/} -### Hydrating server-rendered HTML {/*hydrating-server-rendered-html*/} +### Гидратация HTML, отрисованного на сервере {/*hydrating-server-rendered-html*/} -If your app's HTML was generated by [`react-dom/server`](/reference/react-dom/client/createRoot), you need to *hydrate* it on the client. +Если HTML вашего приложения был сгенерирован [`react-dom/server`](/reference/react-dom/client/createRoot), вам нужно *гидрировать* его на клиенте. ```js [[1, 3, "document.getElementById('root')"], [2, 3, ""]] import { hydrateRoot } from 'react-dom/client'; @@ -131,16 +130,16 @@ import { hydrateRoot } from 'react-dom/client'; hydrateRoot(document.getElementById('root'), ); ``` -This will hydrate the server HTML inside the browser DOM node with the React component for your app. Usually, you will do it once at startup. If you use a framework, it might do this behind the scenes for you. +Это гидрирует HTML сервера внутри DOM-узла браузера с помощью компонента React вашего приложения. Обычно вы делаете это один раз при запуске. Если вы используете фреймворк, он может сделать это за вас в фоновом режиме. -To hydrate your app, React will "attach" your components' logic to the initial generated HTML from the server. Hydration turns the initial HTML snapshot from the server into a fully interactive app that runs in the browser. +Чтобы гидрировать ваше приложение, React «прикрепит» логику ваших компонентов к начальному HTML, сгенерированному сервером. Гидратация превращает начальный снимок HTML с сервера в полностью интерактивное приложение, которое работает в браузере. ```html public/index.html

Hello, world!

``` @@ -180,30 +179,30 @@ function Counter() {
-You shouldn't need to call `hydrateRoot` again or to call it in more places. From this point on, React will be managing the DOM of your application. To update the UI, your components will [use state](/reference/react/useState) instead. +Вам не нужно будет снова вызывать `hydrateRoot` или вызывать его в других местах. С этого момента React будет управлять DOM вашего приложения. Чтобы обновлять UI, ваши компоненты будут использовать [состояние](/reference/react/useState) вместо этого. -The React tree you pass to `hydrateRoot` needs to produce **the same output** as it did on the server. +React-дерево, которое вы передаете в `hydrateRoot`, должно производить **тот же вывод**, что и на сервере. -This is important for the user experience. The user will spend some time looking at the server-generated HTML before your JavaScript code loads. Server rendering creates an illusion that the app loads faster by showing the HTML snapshot of its output. Suddenly showing different content breaks that illusion. This is why the server render output must match the initial render output on the client. +Это важно для пользовательского опыта. Пользователь будет некоторое время смотреть на HTML, сгенерированный сервером, до того, как ваш JavaScript-код загрузится. Серверный рендеринг создает иллюзию более быстрой загрузки приложения, показывая снимок его вывода в виде HTML. Внезапное отображение другого содержимого нарушает эту иллюзию. Именно поэтому вывод серверного рендеринга должен совпадать с выводом начального рендеринга на клиенте. -The most common causes leading to hydration errors include: +Наиболее распространенные причины ошибок гидратации включают: -* Extra whitespace (like newlines) around the React-generated HTML inside the root node. -* Using checks like `typeof window !== 'undefined'` in your rendering logic. -* Using browser-only APIs like [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) in your rendering logic. -* Rendering different data on the server and the client. +* Дополнительные пробелы (например, переносы строк) вокруг HTML, сгенерированного React, внутри корневого узла. +* Использование проверок, таких как `typeof window !== 'undefined'` в вашей логике рендеринга. +* Использование API, доступных только в браузере, таких как [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) в вашей логике рендеринга. +* Рендеринг различных данных на сервере и клиенте. -React recovers from some hydration errors, but **you must fix them like other bugs.** In the best case, they'll lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements. +React восстанавливается после некоторых ошибок гидратации, но **вы должны исправлять их, как и другие ошибки.** В лучшем случае они приведут к замедлению работы; в худшем случае обработчики событий могут быть прикреплены к неправильным элементам. --- -### Hydrating an entire document {/*hydrating-an-entire-document*/} +### Гидратация всего документа {/*hydrating-an-entire-document*/} -Apps fully built with React can render the entire document as JSX, including the [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) tag: +Приложения, полностью построенные с использованием React, могут отрисовывать весь документ как JSX, включая тег [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html): ```js {3,13} function App() { @@ -223,7 +222,7 @@ function App() { } ``` -To hydrate the entire document, pass the [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) global as the first argument to `hydrateRoot`: +Чтобы гидрировать весь документ, передайте глобальный объект [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) в качестве первого аргумента `hydrateRoot`: ```js {4} import { hydrateRoot } from 'react-dom/client'; @@ -234,18 +233,18 @@ hydrateRoot(document, ); --- -### Suppressing unavoidable hydration mismatch errors {/*suppressing-unavoidable-hydration-mismatch-errors*/} +### Подавление неизбежных ошибок расхождения при гидратации {/*suppressing-unavoidable-hydration-mismatch-errors*/} -If a single element’s attribute or text content is unavoidably different between the server and the client (for example, a timestamp), you may silence the hydration mismatch warning. +Если атрибут или текстовое содержимое одного элемента неизбежно отличается между сервером и клиентом (например, временная метка), вы можете подавить предупреждение о расхождении при гидратации. -To silence hydration warnings on an element, add `suppressHydrationWarning={true}`: +Чтобы подавить предупреждения гидратации для элемента, добавьте `suppressHydrationWarning={true}`: ```html public/index.html

Current Date: 01/01/2020

``` @@ -270,20 +269,20 @@ export default function App() {
-This only works one level deep, and is intended to be an escape hatch. Don’t overuse it. React will **not** attempt to patch mismatched text content. +Это работает только на одном уровне вложенности и предназначено для использования в крайних случаях. Не злоупотребляйте этим. React **не** будет пытаться исправить несовпадающее текстовое содержимое. --- -### Handling different client and server content {/*handling-different-client-and-server-content*/} +### Обработка различного содержимого клиента и сервера {/*handling-different-client-and-server-content*/} -If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a [state variable](/reference/react/useState) like `isClient`, which you can set to `true` in an [Effect](/reference/react/useEffect): +Если вам намеренно нужно отрисовать что-то разное на сервере и клиенте, вы можете выполнить рендеринг в два прохода. Компоненты, которые отрисовывают что-то разное на клиенте, могут считывать [переменную состояния](/reference/react/useState), такую как `isClient`, которую вы можете установить в `true` в [Effect](/reference/react/useEffect): ```html public/index.html

Is Server

``` @@ -316,28 +315,28 @@ export default function App() {
-This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration. +Таким образом, первый проход рендеринга отрисует то же содержимое, что и сервер, избегая расхождений, но дополнительный проход будет выполнен синхронно сразу после гидратации. -This approach makes hydration slower because your components have to render twice. Be mindful of the user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so rendering a different UI immediately after hydration may also feel jarring to the user. +Этот подход замедляет гидратацию, поскольку ваши компоненты должны рендериться дважды. Помните о пользовательском опыте при медленных соединениях. Код JavaScript может загрузиться значительно позже начального рендеринга HTML, поэтому рендеринг другого UI сразу после гидратации также может показаться пользователю резким. --- -### Updating a hydrated root component {/*updating-a-hydrated-root-component*/} +### Обновление гидрированного корневого компонента {/*updating-a-hydrated-root-component*/} -After the root has finished hydrating, you can call [`root.render`](#root-render) to update the root React component. **Unlike with [`createRoot`](/reference/react-dom/client/createRoot), you don't usually need to do this because the initial content was already rendered as HTML.** +После того как корневой узел закончит гидратацию, вы можете вызвать [`root.render`](#root-render) для обновления корневого компонента React. **В отличие от [`createRoot`](/reference/react-dom/client/createRoot), вам обычно не нужно делать это, поскольку начальное содержимое уже было отрисовано как HTML.** -If you call `root.render` at some point after hydration, and the component tree structure matches up with what was previously rendered, React will [preserve the state.](/learn/preserving-and-resetting-state) Notice how you can type in the input, which means that the updates from repeated `render` calls every second in this example are not destructive: +Если вы вызовете `root.render` в какой-то момент после гидратации, и структура дерева компонентов совпадет с ранее отрисованной, React [сохранит состояние.](/learn/preserving-and-resetting-state) Обратите внимание, как вы можете вводить текст в поле ввода, что означает, что обновления от повторяющихся вызовов `render` каждую секунду в этом примере не являются разрушительными: ```html public/index.html

Hello, world! 0

``` @@ -372,11 +371,11 @@ export default function App({counter}) {
-It is uncommon to call [`root.render`](#root-render) on a hydrated root. Usually, you'll [update state](/reference/react/useState) inside one of the components instead. +Вызывать [`root.render`](#root-render) для гидрированного корневого узла нечасто. Обычно вы будете [обновлять состояние](/reference/react/useState) внутри одного из компонентов вместо этого. -### Error logging in production {/*error-logging-in-production*/} +### Логирование ошибок в продакшене {/*error-logging-in-production*/} -By default, React will log all errors to the console. To implement your own error reporting, you can provide the optional error handler root options `onUncaughtError`, `onCaughtError` and `onRecoverableError`: +По умолчанию React будет записывать все ошибки в консоль. Чтобы реализовать собственную отчетность об ошибках, вы можете предоставить необязательные параметры корневого узла для обработки ошибок: `onUncaughtError`, `onCaughtError` и `onRecoverableError`: ```js [[1, 7, "onCaughtError"], [2, 7, "error", 1], [3, 7, "errorInfo"], [4, 11, "componentStack", 15]] import { hydrateRoot } from "react-dom/client"; @@ -396,19 +395,19 @@ const root = hydrateRoot(container, , { }); ``` -The onCaughtError option is a function called with two arguments: +Параметр onCaughtError — это функция, вызываемая с двумя аргументами: -1. The error that was thrown. -2. An errorInfo object that contains the componentStack of the error. +1. Ошибка, которая была выброшена. +2. Объект errorInfo, который содержит componentStack ошибки. -Together with `onUncaughtError` and `onRecoverableError`, you can implement your own error reporting system: +Вместе с `onUncaughtError` и `onRecoverableError` вы можете реализовать собственную систему отчетности об ошибках: ```js src/reportError.js function reportError({ type, error, errorInfo }) { - // The specific implementation is up to you. - // `console.error()` is only used for demonstration purposes. + // Конкретная реализация зависит от вас. + // `console.error()` используется только в демонстрационных целях. console.error(type, error, "Component Stack: "); console.error("Component Stack: ", errorInfo.componentStack); } @@ -439,9 +438,9 @@ import { const container = document.getElementById("root"); hydrateRoot(container, , { - // Keep in mind to remove these options in development to leverage - // React's default handlers or implement your own overlay for development. - // The handlers are only specfied unconditionally here for demonstration purposes. + // Имейте в виду, что в режиме разработки следует удалить эти параметры, + // чтобы использовать стандартные обработчики React или реализовать свой собственный оверлей для разработки. + // Обработчики указаны здесь безусловно только в демонстрационных целях. onCaughtError: onCaughtErrorProd, onRecoverableError: onRecoverableErrorProd, onUncaughtError: onUncaughtErrorProd, @@ -501,7 +500,7 @@ export default function App() {
Server content before hydration.
@@ -509,12 +508,12 @@ export default function App() { ```
-## Troubleshooting {/*troubleshooting*/} +## Устранение неполадок {/*troubleshooting*/} -### I'm getting an error: "You passed a second argument to root.render" {/*im-getting-an-error-you-passed-a-second-argument-to-root-render*/} +### Я получаю ошибку: "You passed a second argument to root.render" {/*im-getting-an-error-you-passed-a-second-argument-to-root-render*/} -A common mistake is to pass the options for `hydrateRoot` to `root.render(...)`: +Распространенная ошибка — передача параметров для `hydrateRoot` в `root.render(...)`: @@ -522,11 +521,11 @@ Warning: You passed a second argument to root.render(...) but it only accepts on -To fix, pass the root options to `hydrateRoot(...)`, not `root.render(...)`: +Чтобы исправить это, передайте параметры корневого узла в `hydrateRoot(...)`, а не в `root.render(...)`: ```js {2,5} -// 🚩 Wrong: root.render only takes one argument. +// 🚩 Неправильно: root.render принимает только один аргумент. root.render(App, {onUncaughtError}); -// ✅ Correct: pass options to createRoot. +// ✅ Правильно: передайте параметры в createRoot. const root = hydrateRoot(container, , {onUncaughtError}); -``` +``` \ No newline at end of file