diff --git a/src/content/reference/react/StrictMode.md b/src/content/reference/react/StrictMode.md index b7ca2227c..c7efac968 100644 --- a/src/content/reference/react/StrictMode.md +++ b/src/content/reference/react/StrictMode.md @@ -5,7 +5,7 @@ title: -`` lets you find common bugs in your components early during development. +`` позволяет вам обнаружить распространенные баги в ваших компонентах на ранних этапах разработки. ```js @@ -20,11 +20,11 @@ title: --- -## Reference {/*reference*/} +## Справочник {/*reference*/} ### `` {/*strictmode*/} -Use `StrictMode` to enable additional development behaviors and warnings for the component tree inside: +Используйте `StrictMode` для активации дополнительных проверок и предупреждений для вложенного дерева компонентов: ```js import { StrictMode } from 'react'; @@ -38,32 +38,32 @@ root.render( ); ``` -[See more examples below.](#usage) +[Больше примеров использования ниже.](#usage) -Strict Mode enables the following development-only behaviors: +Строгий режим активирует следующие варианты поведения в режиме разработки: -- Your components will [re-render an extra time](#fixing-bugs-found-by-double-rendering-in-development) to find bugs caused by impure rendering. -- Your components will [re-run Effects an extra time](#fixing-bugs-found-by-re-running-effects-in-development) to find bugs caused by missing Effect cleanup. -- Your components will [be checked for usage of deprecated APIs.](#fixing-deprecation-warnings-enabled-by-strict-mode) +- Ваши компоненты будут [рендерится повторно](#fixing-bugs-found-by-double-rendering-in-development), чтобы можно было найти баги, вызванные нечистым рендерингом. +- Ваши компоненты будут [повторно запускать эффекты](#fixing-bugs-found-by-re-running-effects-in-development), чтобы можно было найти баги, возникающие из-за отсутствия сброса эффекта. +- Ваши компоненты будут [проверяться на использование устаревших API.](#fixing-deprecation-warnings-enabled-by-strict-mode) -#### Props {/*props*/} +#### Пропсы {/*props*/} -`StrictMode` accepts no props. +`StrictMode` не принимает никаких пропсов. -#### Caveats {/*caveats*/} +#### Предостережения {/*caveats*/} -* There is no way to opt out of Strict Mode inside a tree wrapped in ``. This gives you confidence that all components inside `` are checked. If two teams working on a product disagree whether they find the checks valuable, they need to either reach consensus or move `` down in the tree. +* Если вы используете ``, то не сможете отключить его для части дерева. Это гарантирует, что все компоненты внутри `` проходят проверки. Если две команды, работающие над продуктом, не могут прийти к соглашению, нужны ли им эти проверки, то они должны либо достичь компромисса, либо переместить `` ниже по дереву. --- -## Usage {/*usage*/} +## Применение {/*usage*/} -### Enabling Strict Mode for entire app {/*enabling-strict-mode-for-entire-app*/} +### Как включить строгий режим для всего приложения {/*enabling-strict-mode-for-entire-app*/} -Strict Mode enables extra development-only checks for the entire component tree inside the `` component. These checks help you find common bugs in your components early in the development process. +Строгий режим включает дополнительные проверки для всего дерева компонентов внутри `` в режиме разработки. Эти проверки позволяют находить распространенные баги в компонентах на ранней стадии разработки. -To enable Strict Mode for your entire app, wrap your root component with `` when you render it: +Чтобы включить строгий режим для всего приложения, оберните ваш корень вашего приложения в `` при рендеринге: ```js {6,8} import { StrictMode } from 'react'; @@ -77,27 +77,27 @@ root.render( ); ``` -We recommend wrapping your entire app in Strict Mode, especially for newly created apps. If you use a framework that calls [`createRoot`](/reference/react-dom/client/createRoot) for you, check its documentation for how to enable Strict Mode. +Мы рекомендуем целиком оборачивать ваше приложение (особенно, если оно новое) в строгий режим. Если вы используете фреймворк, который вызывает за вас [`createRoot`](/reference/react-dom/client/createRoot), посмотрите как включить строгий режим в его документации. -Although the Strict Mode checks **only run in development,** they help you find bugs that already exist in your code but can be tricky to reliably reproduce in production. Strict Mode lets you fix bugs before your users report them. +Несмотря на то, что проверки строгого режима **выполняются только в режиме разработки,** они помогают вам находить ошибки, которые уже существуют в вашем коде, и их может быть сложно стабильно воспроизвести в продакшене. Строгий режим позволяет исправлять такие ошибки до того, как ваши пользователи сообщат о них. -Strict Mode enables the following checks in development: +Строгий режим включает следующие дополнительные проверки в режиме разработки: -- Your components will [re-render an extra time](#fixing-bugs-found-by-double-rendering-in-development) to find bugs caused by impure rendering. -- Your components will [re-run Effects an extra time](#fixing-bugs-found-by-re-running-effects-in-development) to find bugs caused by missing Effect cleanup. -- Your components will [be checked for usage of deprecated APIs.](#fixing-deprecation-warnings-enabled-by-strict-mode) +- Ваши компоненты будут [рендерится повторно](#fixing-bugs-found-by-double-rendering-in-development), чтобы можно было найти баги, вызванные нечистым рендерингом. +- Ваши компоненты будут [повторно запускать эффекты](#fixing-bugs-found-by-re-running-effects-in-development), чтобы можно было найти баги, возникающие из-за отсутствия сброса эффекта. +- Ваши компоненты будут [проверяться на использование устаревших API.](#fixing-deprecation-warnings-enabled-by-strict-mode) -**All of these checks are development-only and do not impact the production build.** +**Все эти проверки работают только в режиме разработки и не оказывают никакого эффекта в продакшен-сборке.** --- -### Enabling strict mode for a part of the app {/*enabling-strict-mode-for-a-part-of-the-app*/} +### Активация строгого режима для части приложения {/*enabling-strict-mode-for-a-part-of-the-app*/} -You can also enable Strict Mode for any part of your application: +Вы можете активировать строгий режим для любой части вашего приложения: ```js {7,12} import { StrictMode } from 'react'; @@ -118,25 +118,25 @@ function App() { } ``` -In this example, Strict Mode checks will not run against the `Header` and `Footer` components. However, they will run on `Sidebar` and `Content`, as well as all of the components inside them, no matter how deep. +В этом примере проверки строгого режима не будут выполняться для компонентов `Header` и `Footer`. Однако, они будут выполняться для `Sidebar` и `Content`, а также для всех компонентов внутри них, независимо от глубины вложенности. --- -### Fixing bugs found by double rendering in development {/*fixing-bugs-found-by-double-rendering-in-development*/} +### Исправление багов, найденных повторным рендерингом в режиме разработки {/*fixing-bugs-found-by-double-rendering-in-development*/} -[React assumes that every component you write is a pure function.](/learn/keeping-components-pure) This means that React components you write must always return the same JSX given the same inputs (props, state, and context). +[React предполагает, что каждый компонент является чистой функцией.](/learn/keeping-components-pure) Это значит, что React-компоненты, которые вы создаёте, должны всегда возвращать тот же JSX при одинаковых параметрах (пропсах, состоянии и контексте). -Components breaking this rule behave unpredictably and cause bugs. To help you find accidentally impure code, Strict Mode calls some of your functions (only the ones that should be pure) **twice in development.** This includes: +Компоненты, которые нарушают это правило, работают непостоянно и приводят к ошибкам. Чтобы помочь вам обнаружить случайно нечистый код, строгий режим запускает некоторые из ваших функций (только те, которые должны быть чистыми) **два раза в режиме разработки.** Это касается: -- Your component function body (only top-level logic, so this doesn't include code inside event handlers) -- Functions that you pass to [`useState`](/reference/react/useState), [`set` functions](/reference/react/useState#setstate), [`useMemo`](/reference/react/useMemo), or [`useReducer`](/reference/react/useReducer) -- Some class component methods like [`constructor`](/reference/react/Component#constructor), [`render`](/reference/react/Component#render), [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) ([see the whole list](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects)) +- Тело функции компонента (только логика верхнего уровня, без учета кода внутри обработчиков событий) +- Функции, которые передаются в функции [`useState`](/reference/react/useState), [`set` функции](/reference/react/useState#setstate), [`useMemo`](/reference/react/useMemo), или [`useReducer`](/reference/react/useReducer) +- Некоторые методы классовых компонентов, такие как [`constructor`](/reference/react/Component#constructor), [`render`](/reference/react/Component#render), [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) ([полный список](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects)) -If a function is pure, running it twice does not change its behavior because a pure function produces the same result every time. However, if a function is impure (for example, it mutates the data it receives), running it twice tends to be noticeable (that's what makes it impure!) This helps you spot and fix the bug early. +Если функция является чистой, то её повторный запуск не меняет её поведения, потому что чистая функция всегда даёт одинаковый результат. Но если функция является нечистой (например, мутирует получаемые данные), то её повторный запуск обычно заметен (это и делает её нечистой!). Это помогает вам быстрее находить и исправлять баг. -**Here is an example to illustrate how double rendering in Strict Mode helps you find bugs early.** +**Вот пример, который показывает, как повторный рендеринг в строгом режиме помогает вам находить баги на ранней стадии.** -This `StoryTray` component takes an array of `stories` and adds one last "Create Story" item at the end: +Компонент `StoryTray` принимает массив `stories` и добавляет в конец этого массива один элемент "Create Story": @@ -212,9 +212,9 @@ li { -There is a mistake in the code above. However, it is easy to miss because the initial output appears correct. +В коде выше закралась ошибка. Но её не так просто заметить, потому что на первый взгляд всё выглядит правильно. -This mistake will become more noticeable if the `StoryTray` component re-renders multiple times. For example, let's make the `StoryTray` re-render with a different background color whenever you hover over it: +Ошибка станет более заметной, если компонент `StoryTray` будет отрендерен несколько раз. Например, давайте сделаем так, чтобы `StoryTray` рендерился с другим цветом фона каждый раз, когда вы наводите на него курсор: @@ -299,20 +299,20 @@ li { -Notice how every time you hover over the `StoryTray` component, "Create Story" gets added to the list again. The intention of the code was to add it once at the end. But `StoryTray` directly modifies the `stories` array from the props. Every time `StoryTray` renders, it adds "Create Story" again at the end of the same array. In other words, `StoryTray` is not a pure function--running it multiple times produces different results. +Заметьте, как каждый раз, когда вы наводите курсор мыши на компонент `StoryTray`, "Create Story" снова добавляется в массив еще раз. Целью кода было добавить его лишь один раз в конец. Но `StoryTray` напрямую изменяет массив `stories` из пропсов. Каждый раз, когда `StoryTray` рендерится, элемент "Create Story" снова добавляется в конец того же самого массива. Другими словами, `StoryTray` не является чистой функцией -- её многократный запуск приводит к разным результатам. -To fix this problem, you can make a copy of the array, and modify that copy instead of the original one: +Чтобы исправить эту проблему, вы можете создать копию массива и изменять её вместо оригинального массива: ```js {2} export default function StoryTray({ stories }) { - const items = stories.slice(); // Clone the array - // ✅ Good: Pushing into a new array + const items = stories.slice(); // Клонируем массив + // ✅ Хорошо: Добавляем элемент в новый массив items.push({ id: 'create', label: 'Create Story' }); ``` -This would [make the `StoryTray` function pure.](/learn/keeping-components-pure) Each time it is called, it would only modify a new copy of the array, and would not affect any external objects or variables. This solves the bug, but you had to make the component re-render more often before it became obvious that something is wrong with its behavior. +Это бы [сделало функцию `StoryTray` чистой.](/learn/keeping-components-pure) Каждый раз, когда она вызывается, она бы только изменяла новую копию массива и не влияла бы на какие-либо внешние объекты или переменные. Это решает проблему, но вам пришлось заставить компонент рендериться чаще, прежде чем стало очевидно, что его поведение некорректное. -**In the original example, the bug wasn't obvious. Now let's wrap the original (buggy) code in ``:** +**В оригинальном примере ошибка не была очевидной. Теперь давайте обернем исходный (с ошибкой) код в ``:** @@ -393,7 +393,7 @@ li { -**Strict Mode *always* calls your rendering function twice, so you can see the mistake right away** ("Create Story" appears twice). This lets you notice such mistakes early in the process. When you fix your component to render in Strict Mode, you *also* fix many possible future production bugs like the hover functionality from before: +**Строгий режим *всегда* вызывает функцию рендеринга дважды, поэтому вы сразу же можете увидеть ошибку** ("Create Story" появляется дважды). Это позволяет замечать такие ошибки на ранней стадии разработки. Когда вы заставляете ваш компонент работать в строгом режиме, вы *также* устраняете множество потенциальных багов в продакшене, таких, как поведение при наведении мыши из предыдущего примера: @@ -442,7 +442,7 @@ import { useState } from 'react'; export default function StoryTray({ stories }) { const [isHover, setIsHover] = useState(false); - const items = stories.slice(); // Clone the array + const items = stories.slice(); // Клонируем массив items.push({ id: 'create', label: 'Create Story' }); return (
    -Without Strict Mode, it was easy to miss the bug until you added more re-renders. Strict Mode made the same bug appear right away. Strict Mode helps you find bugs before you push them to your team and to your users. +Без строгого режима было легко пропустить ошибку, пока вы не добавили больше ре-рендеров. Строгий режим выявил эту ошибку сразу. Строгий режим спасает вас от ошибок, которые могут испортить работу вашей команды и вызывать проблемы у ваших пользователей. -[Read more about keeping components pure.](/learn/keeping-components-pure) +[Подробнее о том, как сохранять компоненты чистыми.](/learn/keeping-components-pure) -If you have [React DevTools](/learn/react-developer-tools) installed, any `console.log` calls during the second render call will appear slightly dimmed. React DevTools also offers a setting (off by default) to suppress them completely. +Если у вас установлены [React DevTools](/learn/react-developer-tools), любые вызовы `console.log` во время повторного рендеринга будут выглядеть менее ярко. React DevTools также имеет настройку (выключена по умолчанию) для их полного отключения. --- -### Fixing bugs found by re-running Effects in development {/*fixing-bugs-found-by-re-running-effects-in-development*/} +### Исправление багов, найденных при повторном запуске эффектов в режиме разработки {/*fixing-bugs-found-by-re-running-effects-in-development*/} -Strict Mode can also help find bugs in [Effects.](/learn/synchronizing-with-effects) +Строгий режим также помогает находить ошибки в [эффектах.](/learn/synchronizing-with-effects) -Every Effect has some setup code and may have some cleanup code. Normally, React calls setup when the component *mounts* (is added to the screen) and calls cleanup when the component *unmounts* (is removed from the screen). React then calls cleanup and setup again if its dependencies changed since the last render. +Каждый эффект имеет свой код установки и, возможно, код для сброса. Обычно React вызывает код установки, при *монтировании* компонента (его добавлении на экран) и вызывает сброс при *размонтировании* компонента (его удалении с экрана). Если зависимости эффекта изменилис с момента последнего рендера, React вызывает сброс и установку заново. -When Strict Mode is on, React will also run **one extra setup+cleanup cycle in development for every Effect.** This may feel surprising, but it helps reveal subtle bugs that are hard to catch manually. +Когда строгий режим включен, React будет запускать **один дополнительный цикл установки и сброса для каждого эффекта в режиме разработки.** Это может быть неожиданным, но это помогает находить баги, которые сложно отловить вручную. -**Here is an example to illustrate how re-running Effects in Strict Mode helps you find bugs early.** +**Вот пример, иллюстрирующий то, как повторный запуск эффектов в строгом режиме помогает вам находить баги на ранней стадии.** -Consider this example that connects a component to a chat: +Рассмотрим пример, в котором компонент подключается к чату: @@ -539,17 +539,17 @@ export default function ChatRoom() { let connections = 0; export function createConnection(serverUrl, roomId) { - // A real implementation would actually connect to the server + // Настоящий код, который действительно подключается к серверу return { connect() { - console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); + console.log('✅ Подключение к комнате "' + roomId + '" по адресу ' + serverUrl + '...'); connections++; - console.log('Active connections: ' + connections); + console.log('Активных подключений: ' + connections); }, disconnect() { - console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); + console.log('❌ Отключение от комнаты "' + roomId + '" по адресу ' + serverUrl); connections--; - console.log('Active connections: ' + connections); + console.log('Активных подключений: ' + connections); } }; } @@ -562,9 +562,9 @@ button { margin-left: 10px; } -There is an issue with this code, but it might not be immediately clear. +В коде есть проблема, но, возможно, это не сразу очевидно. -To make the issue more obvious, let's implement a feature. In the example below, `roomId` is not hardcoded. Instead, the user can select the `roomId` that they want to connect to from a dropdown. Click "Open chat" and then select different chat rooms one by one. Keep track of the number of active connections in the console: +Для того чтобы проблема стала более очевидной, давайте добавим новую функциональность. В примере ниже, `roomId` не зашит в коде, а пользователь может выбрать `roomId`, к которому он хочет подключиться, из выпадающего списка. Нажмите на "Open chat" и выберите разные чаты один за другим. Следите за количеством активных подключений в консоли: @@ -623,17 +623,17 @@ export default function App() { let connections = 0; export function createConnection(serverUrl, roomId) { - // A real implementation would actually connect to the server + // Настоящий код, который действительно подключается к серверу return { connect() { - console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); + console.log('✅ Подключение к комнате "' + roomId + '" по адресу ' + serverUrl + '...'); connections++; - console.log('Active connections: ' + connections); + console.log('Активных подключений: ' + connections); }, disconnect() { - console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); + console.log('❌ Отключение от комнаты "' + roomId + '" по адресу ' + serverUrl); connections--; - console.log('Active connections: ' + connections); + console.log('Активных подключений: ' + connections); } }; } @@ -646,7 +646,7 @@ button { margin-left: 10px; } -You'll notice that the number of open connections always keeps growing. In a real app, this would cause performance and network problems. The issue is that [your Effect is missing a cleanup function:](/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed) +Вы заметите, что число открытых подключений продолжает расти. В реальном приложении это может вызывать проблемы с сетью и производительностью. Проблема заключается в том, что [ваш эффект не содержит функцию сброса:](/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed) ```js {4} useEffect(() => { @@ -656,9 +656,9 @@ You'll notice that the number of open connections always keeps growing. In a rea }, [roomId]); ``` -Now that your Effect "cleans up" after itself and destroys the outdated connections, the leak is solved. However, notice that the problem did not become visible until you've added more features (the select box). +Теперь, когда ваш эффект "убирает" за собой устаревшие подключения, утечка устранена. Обратите внимание, что проблема не стала заметной, пока вы не добавили больше функциональности (выпадающий список). -**In the original example, the bug wasn't obvious. Now let's wrap the original (buggy) code in ``:** +**В исходном примере баг не был очевидным. Теперь давайте обернём исходный код (с багом) в ``:** @@ -697,17 +697,17 @@ export default function ChatRoom() { let connections = 0; export function createConnection(serverUrl, roomId) { - // A real implementation would actually connect to the server + // Настоящий код, который действительно подключается к серверу return { connect() { - console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); + console.log('✅ Подключение к комнате "' + roomId + '" по адресу ' + serverUrl + '...'); connections++; - console.log('Active connections: ' + connections); + console.log('Активных подключений: ' + connections); }, disconnect() { - console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); + console.log('❌ Отключение от комнаты "' + roomId + '" по адресу ' + serverUrl); connections--; - console.log('Active connections: ' + connections); + console.log('Активных подключений: ' + connections); } }; } @@ -720,9 +720,9 @@ button { margin-left: 10px; } -**With Strict Mode, you immediately see that there is a problem** (the number of active connections jumps to 2). Strict Mode runs an extra setup+cleanup cycle for every Effect. This Effect has no cleanup logic, so it creates an extra connection but doesn't destroy it. This is a hint that you're missing a cleanup function. +**Благодаря строгому режиму вы сразу видите проблему** (количество активных подключений увеличивается до 2). Строгий режим запускает дополнительный цикл установки и сброса для каждого эффекта. У этого эффекта отсутствует логика сброса, поэтому он создаёт дополнительное подключение и не удаляет его. Это подсказка, что в эффекте отсутствует функция сброса. -Strict Mode lets you notice such mistakes early in the process. When you fix your Effect by adding a cleanup function in Strict Mode, you *also* fix many possible future production bugs like the select box from before: +Строгий режим позволяет вам заметить подобные ошибки на ранней стадии разработки. Когда вы поправите ваш эффект, добавляя сбрасывающую функцию сброса в строгом режиме, вы *также* поправите множество потенциальных багов продакшена, например, как с выпадающим списком, который мы рассматривали ранее: @@ -787,17 +787,17 @@ export default function App() { let connections = 0; export function createConnection(serverUrl, roomId) { - // A real implementation would actually connect to the server + // Настоящий код, который действительно подключается к серверу return { connect() { - console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); + console.log('✅ Подключение к комнате "' + roomId + '" по адресу ' + serverUrl + '...'); connections++; - console.log('Active connections: ' + connections); + console.log('Активных подключений: ' + connections); }, disconnect() { - console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); + console.log('❌ Отключение от комнаты "' + roomId + '" по адресу ' + serverUrl); connections--; - console.log('Active connections: ' + connections); + console.log('Активных подключений: ' + connections); } }; } @@ -810,21 +810,21 @@ button { margin-left: 10px; } -Notice how the active connection count in the console doesn't keep growing anymore. +Обратите внимание, что количество активных подключений в консоли больше не растёт. -Without Strict Mode, it was easy to miss that your Effect needed cleanup. By running *setup → cleanup → setup* instead of *setup* for your Effect in development, Strict Mode made the missing cleanup logic more noticeable. +Без строгого режима было легко пропустить, что у вашего эффекта отсутствует функция сброса. Благодаря вызову *установка → сброс → установка* вместо *установка* для вашего эффекта в режиме разработки, строгий режим сделал отсутствие функции сброса более заметным. -[Read more about implementing Effect cleanup.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) +[Узнать больше о функции сброса эффекта.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) --- -### Fixing deprecation warnings enabled by Strict Mode {/*fixing-deprecation-warnings-enabled-by-strict-mode*/} +### Исправление предупреждений об устаревших методах в строгом режиме {/*fixing-deprecation-warnings-enabled-by-strict-mode*/} -React warns if some component anywhere inside a `` tree uses one of these deprecated APIs: +React предупреждает, если какой-либо компонент внутри дерева `` использует одно из следующих устаревших API: -* [`findDOMNode`](/reference/react-dom/findDOMNode). [See alternatives.](https://reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) -* `UNSAFE_` class lifecycle methods like [`UNSAFE_componentWillMount`](/reference/react/Component#unsafe_componentwillmount). [See alternatives.](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles) -* Legacy context ([`childContextTypes`](/reference/react/Component#static-childcontexttypes), [`contextTypes`](/reference/react/Component#static-contexttypes), and [`getChildContext`](/reference/react/Component#getchildcontext)). [See alternatives.](/reference/react/createContext) -* Legacy string refs ([`this.refs`](/reference/react/Component#refs)). [See alternatives.](https://reactjs.org/docs/strict-mode.html#warning-about-legacy-string-ref-api-usage) +* [`findDOMNode`](/reference/react-dom/findDOMNode). [Смотреть альтернативные решения.](https://reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) +* `UNSAFE_` классовые методы жизненного цикла, такие как [`UNSAFE_componentWillMount`](/reference/react/Component#unsafe_componentwillmount). [Смотреть альтернативные решения.](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles) +* Устаревший контекст ([`childContextTypes`](/reference/react/Component#static-childcontexttypes), [`contextTypes`](/reference/react/Component#static-contexttypes), и [`getChildContext`](/reference/react/Component#getchildcontext)). [Смотреть альтернативные решения.](/reference/react/createContext) +* Устаревшие строковые рефы ([`this.refs`](/reference/react/Component#refs)). [Смотреть альтернативные решения.](https://reactjs.org/docs/strict-mode.html#warning-about-legacy-string-ref-api-usage) -These APIs are primarily used in older [class components](/reference/react/Component) so they rarely appear in modern apps. +Эти API в основном используются в старых [классовых компонентах](/reference/react/Component), поэтому они редко встречаются в современных приложениях.