From 5a06c49a555e4eab733312a362ffa92e79bac68e Mon Sep 17 00:00:00 2001 From: "translate-react-bot[bot]" <251169733+translate-react-bot[bot]@users.noreply.github.com> Date: Wed, 13 May 2026 15:30:04 +0000 Subject: [PATCH 1/4] =?UTF-8?q?docs:=20translate=20`react-18-upgrade-guide?= =?UTF-8?q?.md`=20to=20=D0=A0=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../blog/2022/03/08/react-18-upgrade-guide.md | 245 +++++++++--------- 1 file changed, 127 insertions(+), 118 deletions(-) diff --git a/src/content/blog/2022/03/08/react-18-upgrade-guide.md b/src/content/blog/2022/03/08/react-18-upgrade-guide.md index 9d34dfaaa3..5c65f4d3f1 100644 --- a/src/content/blog/2022/03/08/react-18-upgrade-guide.md +++ b/src/content/blog/2022/03/08/react-18-upgrade-guide.md @@ -1,89 +1,90 @@ --- -title: "How to Upgrade to React 18" + +title: "Как обновиться до React 18" author: Rick Hanlon date: 2022/03/08 -description: As we shared in the release post, React 18 introduces features powered by our new concurrent renderer, with a gradual adoption strategy for existing applications. In this post, we will guide you through the steps for upgrading to React 18. +description: Как мы рассказали в публикации о релизе, React 18 представляет новые возможности, основанные на нашем новом конкурентном рендерере, с постепенной стратегией внедрения для существующих приложений. В этой публикации мы расскажем вам, как обновиться до React 18. --- -March 08, 2022 by [Rick Hanlon](https://twitter.com/rickhanlonii) +8 марта 2022 г. от [Rick Hanlon](https://twitter.com/rickhanlonii) --- -As we shared in the [release post](/blog/2022/03/29/react-v18), React 18 introduces features powered by our new concurrent renderer, with a gradual adoption strategy for existing applications. In this post, we will guide you through the steps for upgrading to React 18. +Как мы рассказали в [публикации о релизе](/blog/2022/03/29/react-v18), React 18 представляет новые возможности, основанные на нашем новом конкурентном рендерере, с постепенной стратегией внедрения для существующих приложений. В этой публикации мы расскажем вам, как обновиться до React 18. -Please [report any issues](https://github.com/facebook/react/issues/new/choose) you encounter while upgrading to React 18. +Пожалуйста, [сообщайте о любых проблемах](https://github.com/facebook/react/issues/new/choose), с которыми вы столкнетесь при обновлении до React 18. -For React Native users, React 18 will ship in a future version of React Native. This is because React 18 relies on the New React Native Architecture to benefit from the new capabilities presented in this blogpost. For more information, see the [React Conf keynote here](https://www.youtube.com/watch?v=FZ0cG47msEk&t=1530s). +Для пользователей React Native React 18 будет выпущен в будущей версии React Native. Это связано с тем, что React 18 полагается на новую архитектуру React Native, чтобы воспользоваться новыми возможностями, представленными в этой публикации блога. Для получения дополнительной информации см. [ключевой доклад React Conf здесь](https://www.youtube.com/watch?v=FZ0cG47msEk&t=1530s). --- -## Installing {/*installing*/} +## Установка {/*installing*/} -To install the latest version of React: +Чтобы установить последнюю версию React: ```bash npm install react react-dom ``` -Or if you’re using yarn: +Или, если вы используете yarn: ```bash yarn add react react-dom ``` -## Updates to Client Rendering APIs {/*updates-to-client-rendering-apis*/} +## Обновления API рендеринга на стороне клиента {/*updates-to-client-rendering-apis*/} -When you first install React 18, you will see a warning in the console: +Когда вы впервые установите React 18, вы увидите предупреждение в консоли: -ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot +ReactDOM.render больше не поддерживается в React 18. Вместо этого используйте createRoot. Пока вы не переключитесь на новый API, ваше приложение будет вести себя так, как будто оно работает в React 17. Подробнее: https://reactjs.org/link/switch-to-createroot -React 18 introduces a new root API which provides better ergonomics for managing roots. The new root API also enables the new concurrent renderer, which allows you to opt-into concurrent features. +React 18 представляет новый root API, который обеспечивает лучшую эргономику для управления корнями. Новый root API также включает новый конкурентный рендерер, который позволяет вам использовать конкурентные возможности. ```js -// Before +// До import { render } from 'react-dom'; const container = document.getElementById('app'); render(, container); -// After +// После import { createRoot } from 'react-dom/client'; const container = document.getElementById('app'); const root = createRoot(container); // createRoot(container!) if you use TypeScript root.render(); ``` -We’ve also changed `unmountComponentAtNode` to `root.unmount`: +Мы также изменили `unmountComponentAtNode` на `root.unmount`: ```js -// Before +// До unmountComponentAtNode(container); -// After +// После root.unmount(); ``` -We've also removed the callback from render, since it usually does not have the expected result when using Suspense: +Мы также удалили обратный вызов из render, так как он обычно не дает ожидаемого результата при использовании Suspense: ```js -// Before +// До const container = document.getElementById('app'); render(, container, () => { console.log('rendered'); }); -// After +// После function AppWithCallbackAfterRender() { useEffect(() => { console.log('rendered'); @@ -99,59 +100,59 @@ root.render(); -There is no one-to-one replacement for the old render callback API — it depends on your use case. See the working group post for [Replacing render with createRoot](https://github.com/reactwg/react-18/discussions/5) for more information. +Не существует замены один к одному для старого API обратного вызова render — это зависит от вашего варианта использования. См. публикацию рабочей группы [Замена render на createRoot](https://github.com/reactwg/react-18/discussions/5) для получения дополнительной информации. -Finally, if your app uses server-side rendering with hydration, upgrade `hydrate` to `hydrateRoot`: +Наконец, если ваше приложение использует рендеринг на стороне сервера с гидратацией, обновите `hydrate` до `hydrateRoot`: ```js -// Before +// До import { hydrate } from 'react-dom'; const container = document.getElementById('app'); hydrate(, container); -// After +// После import { hydrateRoot } from 'react-dom/client'; const container = document.getElementById('app'); const root = hydrateRoot(container, ); -// Unlike with createRoot, you don't need a separate root.render() call here. +// В отличие от createRoot, вам не нужен отдельный вызов root.render() здесь. ``` -For more information, see the [working group discussion here](https://github.com/reactwg/react-18/discussions/5). +Для получения дополнительной информации см. [обсуждение рабочей группы здесь](https://github.com/reactwg/react-18/discussions/5). -**If your app doesn't work after upgrading, check whether it's wrapped in ``.** [Strict Mode has gotten stricter in React 18](#updates-to-strict-mode), and not all your components may be resilient to the new checks it adds in development mode. If removing Strict Mode fixes your app, you can remove it during the upgrade, and then add it back (either at the top or for a part of the tree) after you fix the issues that it's pointing out. +**Если ваше приложение не работает после обновления, проверьте, обернуто ли оно в ``.** [Строгий режим стал строже в React 18](#updates-to-strict-mode), и не все ваши компоненты могут быть устойчивы к новым проверкам, которые он добавляет в режиме разработки. Если удаление Strict Mode исправит ваше приложение, вы можете удалить его во время обновления, а затем добавить его обратно (либо вверху, либо для части дерева) после того, как вы исправите проблемы, на которые он указывает. -## Updates to Server Rendering APIs {/*updates-to-server-rendering-apis*/} +## Обновления API рендеринга на стороне сервера {/*updates-to-server-rendering-apis*/} -In this release, we’re revamping our `react-dom/server` APIs to fully support Suspense on the server and Streaming SSR. As part of these changes, we're deprecating the old Node streaming API, which does not support incremental Suspense streaming on the server. +В этом выпуске мы перерабатываем наши API `react-dom/server`, чтобы полностью поддерживать Suspense на сервере и потоковую передачу SSR. В рамках этих изменений мы **устареваем** старый API потоковой передачи Node, который не поддерживает инкрементную потоковую передачу Suspense на сервере. -Using this API will now warn: +Использование этого API теперь будет предупреждать: -* `renderToNodeStream`: **Deprecated ⛔️️** +* `renderToNodeStream`: **Устаревший ⛔️️** -Instead, for streaming in Node environments, use: -* `renderToPipeableStream`: **New ✨** +Вместо этого для потоковой передачи в средах Node используйте: +* `renderToPipeableStream`: **Новый ✨** -We're also introducing a new API to support streaming SSR with Suspense for modern edge runtime environments, such as Deno and Cloudflare workers: -* `renderToReadableStream`: **New ✨** +Мы также представляем новый API для поддержки потоковой передачи SSR с Suspense для современных сред выполнения edge, таких как Deno и Cloudflare workers: +* `renderToReadableStream`: **Новый ✨** -The following APIs will continue working, but with limited support for Suspense: -* `renderToString`: **Limited** ⚠️ -* `renderToStaticMarkup`: **Limited** ⚠️ +Следующие API будут продолжать работать, но с ограниченной поддержкой Suspense: +* `renderToString`: **Ограничено** ⚠️ +* `renderToStaticMarkup`: **Ограничено** ⚠️ -Finally, this API will continue to work for rendering e-mails: +Наконец, этот API будет продолжать работать для рендеринга электронных писем: * `renderToStaticNodeStream` -For more information on the changes to server rendering APIs, see the working group post on [Upgrading to React 18 on the server](https://github.com/reactwg/react-18/discussions/22), a [deep dive on the new Suspense SSR Architecture](https://github.com/reactwg/react-18/discussions/37), and [Shaundai Person’s](https://twitter.com/shaundai) talk on [Streaming Server Rendering with Suspense](https://www.youtube.com/watch?v=pj5N-Khihgc) at React Conf 2021. +Для получения дополнительной информации об изменениях в API рендеринга на стороне сервера см. публикацию рабочей группы [Обновление до React 18 на сервере](https://github.com/reactwg/react-18/discussions/22), [подробный обзор новой архитектуры Suspense SSR](https://github.com/reactwg/react-18/discussions/37) и выступление [Shaundai Person](https://twitter.com/shaundai) о [Потоковой передаче рендеринга на стороне сервера с Suspense](https://www.youtube.com/watch?v=pj5N-Khihgc) на React Conf 2021. -## Updates to TypeScript definitions {/*updates-to-typescript-definitions*/} +## Обновления определений TypeScript {/*updates-to-typescript-definitions*/} -If your project uses TypeScript, you will need to update your `@types/react` and `@types/react-dom` dependencies to the latest versions. The new types are safer and catch issues that used to be ignored by the type checker. The most notable change is that the `children` prop now needs to be listed explicitly when defining props, for example: +Если ваш проект использует TypeScript, вам потребуется обновить ваши зависимости `@types/react` и `@types/react-dom` до последних версий. Новые типы более безопасны и выявляют проблемы, которые раньше игнорировались проверкой типов. Наиболее заметным изменением является то, что проп `children` теперь необходимо указывать явно при определении пропсов, например: ```typescript{3} interface MyButtonProps { @@ -160,51 +161,50 @@ interface MyButtonProps { } ``` -See the [React 18 typings pull request](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210) for a full list of type-only changes. It links to example fixes in library types so you can see how to adjust your code. You can use the [automated migration script](https://github.com/eps1lon/types-react-codemod) to help port your application code to the new and safer typings faster. +См. [запрос на включение типизации React 18](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210) для получения полного списка изменений, касающихся только типов. Он содержит ссылки на исправления примеров в типах библиотек, чтобы вы могли увидеть, как настроить свой код. Вы можете использовать [автоматизированный скрипт миграции](https://github.com/eps1lon/types-react-codemod), чтобы быстрее перенести код вашего приложения на новые и более безопасные типы. -If you find a bug in the typings, please [file an issue](https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/new?category=issues-with-a-types-package) in the DefinitelyTyped repo. +Если вы обнаружите ошибку в типизации, пожалуйста, [создайте ишью](https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/new?category=issues-with-a-types-package) в репозитории DefinitelyTyped. -## Automatic Batching {/*automatic-batching*/} +## Автоматическая группировка {/*automatic-batching*/} -React 18 adds out-of-the-box performance improvements by doing more batching by default. Batching is when React groups multiple state updates into a single re-render for better performance. Before React 18, we only batched updates inside React event handlers. Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default: +React 18 добавляет улучшения производительности из коробки, выполняя больше группировки по умолчанию. Группировка — это когда React группирует несколько обновлений состояния в один повторный рендер для повышения производительности. До React 18 мы группировали обновления только внутри обработчиков событий React. Обновления внутри промисов, setTimeout, нативных обработчиков событий или любых других событий по умолчанию не группировались в React: ```js -// Before React 18 only React events were batched +// До React 18 только события React группировались function handleClick() { setCount(c => c + 1); setFlag(f => !f); - // React will only re-render once at the end (that's batching!) + // React перерендерит только один раз в конце (это группировка!) } setTimeout(() => { setCount(c => c + 1); setFlag(f => !f); - // React will render twice, once for each state update (no batching) + // React перерендерит дважды, по одному разу для каждого обновления состояния (без группировки) }, 1000); ``` - -Starting in React 18 with `createRoot`, all updates will be automatically batched, no matter where they originate from. This means that updates inside of timeouts, promises, native event handlers or any other event will batch the same way as updates inside of React events: +Начиная с React 18 с `createRoot`, все обновления будут автоматически группироваться, независимо от того, откуда они исходят. Это означает, что обновления внутри таймаутов, промисов, нативных обработчиков событий или любых других событий будут группироваться так же, как и обновления внутри событий React: ```js -// After React 18 updates inside of timeouts, promises, -// native event handlers or any other event are batched. +// После React 18 обновления внутри таймаутов, промисов, +// нативных обработчиков событий или любых других событий группируются. function handleClick() { setCount(c => c + 1); setFlag(f => !f); - // React will only re-render once at the end (that's batching!) + // React перерендерит только один раз в конце (это группировка!) } setTimeout(() => { setCount(c => c + 1); setFlag(f => !f); - // React will only re-render once at the end (that's batching!) + // React перерендерит только один раз в конце (это группировка!) }, 1000); ``` -This is a breaking change, but we expect this to result in less work rendering, and therefore better performance in your applications. To opt-out of automatic batching, you can use `flushSync`: +Это критическое изменение, но мы ожидаем, что это приведет к меньшему объему работы по рендерингу и, следовательно, к повышению производительности в ваших приложениях. Чтобы отказаться от автоматической группировки, вы можете использовать `flushSync`: ```js import { flushSync } from 'react-dom'; @@ -213,119 +213,128 @@ function handleClick() { flushSync(() => { setCounter(c => c + 1); }); - // React has updated the DOM by now + // React обновил DOM к настоящему моменту flushSync(() => { setFlag(f => !f); }); - // React has updated the DOM by now + // React обновил DOM к настоящему моменту } ``` -For more information, see the [Automatic batching deep dive](https://github.com/reactwg/react-18/discussions/21). +Для получения дополнительной информации см. [Подробный обзор автоматической группировки](https://github.com/reactwg/react-18/discussions/21). -## New APIs for Libraries {/*new-apis-for-libraries*/} +## Новые API для библиотек {/*new-apis-for-libraries*/} -In the React 18 Working Group we worked with library maintainers to create new APIs needed to support concurrent rendering for use cases specific to their use case in areas like styles, and external stores. To support React 18, some libraries may need to switch to one of the following APIs: +В рабочей группе React 18 мы работали с сопровождающими библиотек, чтобы создать новые API, необходимые для поддержки конкурентного рендеринга для вариантов использования, специфичных для их варианта использования, в таких областях, как стили и внешние хранилища. Чтобы поддержать React 18, некоторым библиотекам может потребоваться переключиться на один из следующих API: -* `useSyncExternalStore` is a new Hook that allows external stores to support concurrent reads by forcing updates to the store to be synchronous. This new API is recommended for any library that integrates with state external to React. For more information, see the [useSyncExternalStore overview post](https://github.com/reactwg/react-18/discussions/70) and [useSyncExternalStore API details](https://github.com/reactwg/react-18/discussions/86). -* `useInsertionEffect` is a new Hook that allows CSS-in-JS libraries to address performance issues of injecting styles in render. Unless you've already built a CSS-in-JS library we don't expect you to ever use this. This Hook will run after the DOM is mutated, but before layout effects read the new layout. This solves an issue that already exists in React 17 and below, but is even more important in React 18 because React yields to the browser during concurrent rendering, giving it a chance to recalculate layout. For more information, see the [Library Upgrade Guide for `