From f7cfbc3a91bd38962c8fc8194f9273d825034519 Mon Sep 17 00:00:00 2001 From: "translate-react-bot[bot]" <251169733+translate-react-bot[bot]@users.noreply.github.com> Date: Wed, 4 Feb 2026 15:12:50 +0000 Subject: [PATCH 1/3] =?UTF-8?q?docs:=20translate=20`Component.md`=20to=20?= =?UTF-8?q?=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 --- src/content/reference/react/Component.md | 620 ++++++++++++----------- 1 file changed, 316 insertions(+), 304 deletions(-) diff --git a/src/content/reference/react/Component.md b/src/content/reference/react/Component.md index 8e58af8ff6..f716517db9 100644 --- a/src/content/reference/react/Component.md +++ b/src/content/reference/react/Component.md @@ -1,16 +1,16 @@ --- -title: Component +title: Компонент --- -We recommend defining components as functions instead of classes. [See how to migrate.](#alternatives) +Мы рекомендуем определять компоненты как функции, а не классы. [Узнайте, как перейти.](#alternatives) -`Component` is the base class for the React components defined as [JavaScript classes.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) Class components are still supported by React, but we don't recommend using them in new code. +`Component` — это базовый класс для React-компонентов, определённых как [классы JavaScript.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) Классовые компоненты по-прежнему поддерживаются React, но мы не рекомендуем использовать их в новом коде. ```js class Greeting extends Component { @@ -26,11 +26,11 @@ class Greeting extends Component { --- -## Reference {/*reference*/} +## Справочник {/*reference*/} ### `Component` {/*component*/} -To define a React component as a class, extend the built-in `Component` class and define a [`render` method:](#render) +Чтобы определить React-компонент как класс, расширьте встроенный класс `Component` и определите метод [`render`.](#render) ```js import { Component } from 'react'; @@ -42,17 +42,17 @@ class Greeting extends Component { } ``` -Only the `render` method is required, other methods are optional. +Обязательным является только метод `render`, остальные методы необязательны. -[See more examples below.](#usage) +[См. больше примеров ниже.](#usage) --- ### `context` {/*context*/} -The [context](/learn/passing-data-deeply-with-context) of a class component is available as `this.context`. It is only available if you specify *which* context you want to receive using [`static contextType`](#static-contexttype). +[Контекст](/learn/passing-data-deeply-with-context) классового компонента доступен как `this.context`. Он доступен только в том случае, если вы укажете, какой именно контекст вы хотите получать, используя [`static contextType`](#static-contexttype). -A class component can only read one context at a time. +Классовый компонент может считывать только один контекст за раз. ```js {2,5} class Button extends Component { @@ -73,9 +73,9 @@ class Button extends Component { -Reading `this.context` in class components is equivalent to [`useContext`](/reference/react/useContext) in function components. +Чтение `this.context` в классовых компонентах эквивалентно [`useContext`](/reference/react/useContext) в функциональных компонентах. -[See how to migrate.](#migrating-a-component-with-context-from-a-class-to-a-function) +[См. как выполнить миграцию.](#migrating-a-component-with-context-from-a-class-to-a-function) @@ -83,7 +83,7 @@ Reading `this.context` in class components is equivalent to [`useContext`](/refe ### `props` {/*props*/} -The props passed to a class component are available as `this.props`. +Пропсы, переданные классовому компоненту, доступны как `this.props`. ```js {3} class Greeting extends Component { @@ -97,9 +97,9 @@ class Greeting extends Component { -Reading `this.props` in class components is equivalent to [declaring props](/learn/passing-props-to-a-component#step-2-read-props-inside-the-child-component) in function components. +Чтение `this.props` в классовых компонентах эквивалентно [объявлению пропсов](/learn/passing-props-to-a-component#step-2-read-props-inside-the-child-component) в функциональных компонентах. -[See how to migrate.](#migrating-a-simple-component-from-a-class-to-a-function) +[См. как выполнить миграцию.](#migrating-a-simple-component-from-a-class-to-a-function) @@ -107,7 +107,7 @@ Reading `this.props` in class components is equivalent to [declaring props](/lea ### `state` {/*state*/} -The state of a class component is available as `this.state`. The `state` field must be an object. Do not mutate the state directly. If you wish to change the state, call `setState` with the new state. +Состояние классового компонента доступно как `this.state`. Поле `state` должно быть объектом. Не изменяйте состояние напрямую. Если вы хотите изменить состояние, вызовите `setState` с новым состоянием. ```js {2-4,7-9,18} class Counter extends Component { @@ -117,7 +117,7 @@ class Counter extends Component { handleAgeChange = () => { this.setState({ - age: this.state.age + 1 + age: this.state.age + 1 }); }; @@ -136,9 +136,9 @@ class Counter extends Component { -Defining `state` in class components is equivalent to calling [`useState`](/reference/react/useState) in function components. +Определение `state` в классовых компонентах эквивалентно вызову [`useState`](/reference/react/useState) в функциональных компонентах. -[See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function) +[См. как выполнить миграцию.](#migrating-a-component-with-state-from-a-class-to-a-function) @@ -146,7 +146,7 @@ Defining `state` in class components is equivalent to calling [`useState`](/refe ### `constructor(props)` {/*constructor*/} -The [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) runs before your class component *mounts* (gets added to the screen). Typically, a constructor is only used for two purposes in React. It lets you declare state and [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) your class methods to the class instance: +[Конструктор](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) выполняется до того, как ваш классовый компонент будет *смонтирован* (добавлен на экран). Обычно конструктор в React используется только для двух целей. Он позволяет объявить состояние и [привязать](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) методы класса к экземпляру класса: ```js {2-6} class Counter extends Component { @@ -161,7 +161,7 @@ class Counter extends Component { } ``` -If you use modern JavaScript syntax, constructors are rarely needed. Instead, you can rewrite this code above using the [public class field syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) which is supported both by modern browsers and tools like [Babel:](https://babeljs.io/) +Если вы используете современный синтаксис JavaScript, конструкторы редко нужны. Вместо этого вы можете переписать приведенный выше код, используя [синтаксис полей класса](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields), который поддерживается как современными браузерами, так и такими инструментами, как [Babel:](https://babeljs.io/) ```js {2,4} class Counter extends Component { @@ -172,31 +172,31 @@ class Counter extends Component { } ``` -A constructor should not contain any side effects or subscriptions. +Конструктор не должен содержать никаких побочных эффектов или подписок. -#### Parameters {/*constructor-parameters*/} +#### Параметры {/*constructor-parameters*/} -* `props`: The component's initial props. +* `props`: Начальные пропсы компонента. -#### Returns {/*constructor-returns*/} +#### Возвращает {/*constructor-returns*/} -`constructor` should not return anything. +`constructor` ничего не должен возвращать. -#### Caveats {/*constructor-caveats*/} +#### Особенности {/*constructor-caveats*/} -* Do not run any side effects or subscriptions in the constructor. Instead, use [`componentDidMount`](#componentdidmount) for that. +* Не выполняйте никаких побочных эффектов или подписок в конструкторе. Вместо этого используйте [`componentDidMount`](#componentdidmount) для этого. -* Inside a constructor, you need to call `super(props)` before any other statement. If you don't do that, `this.props` will be `undefined` while the constructor runs, which can be confusing and cause bugs. +* Внутри конструктора вы должны вызвать `super(props)` перед любым другим оператором. Если вы этого не сделаете, `this.props` будет `undefined` во время выполнения конструктора, что может сбить с толку и вызвать ошибки. -* Constructor is the only place where you can assign [`this.state`](#state) directly. In all other methods, you need to use [`this.setState()`](#setstate) instead. Do not call `setState` in the constructor. +* Конструктор — единственное место, где вы можете напрямую присвоить [`this.state`](#state). Во всех остальных методах вместо этого необходимо использовать [`this.setState()`](#setstate). Не вызывайте `setState` в конструкторе. -* When you use [server rendering,](/reference/react-dom/server) the constructor will run on the server too, followed by the [`render`](#render) method. However, lifecycle methods like `componentDidMount` or `componentWillUnmount` will not run on the server. +* При использовании [серверного рендеринга](/reference/react-dom/server) конструктор также будет выполнен на сервере, за ним последует метод [`render`](#render). Однако методы жизненного цикла, такие как `componentDidMount` или `componentWillUnmount`, не будут выполнены на сервере. -* When [Strict Mode](/reference/react/StrictMode) is on, React will call `constructor` twice in development and then throw away one of the instances. This helps you notice the accidental side effects that need to be moved out of the `constructor`. +* Когда включен [Strict Mode](/reference/react/StrictMode), React дважды вызовет `constructor` в режиме разработки, а затем отбросит один из экземпляров. Это поможет вам заметить случайные побочные эффекты, которые необходимо вынести из `constructor`. -There is no exact equivalent for `constructor` in function components. To declare state in a function component, call [`useState`.](/reference/react/useState) To avoid recalculating the initial state, [pass a function to `useState`.](/reference/react/useState#avoiding-recreating-the-initial-state) +Точного эквивалента для `constructor` в функциональных компонентах нет. Чтобы объявить состояние в функциональном компоненте, вызовите [`useState`.](/reference/react/useState) Чтобы избежать пересчета начального состояния, [передайте функцию в `useState`.](/reference/react/useState#avoiding-recreating-the-initial-state) @@ -204,31 +204,31 @@ There is no exact equivalent for `constructor` in function components. To declar ### `componentDidCatch(error, info)` {/*componentdidcatch*/} -If you define `componentDidCatch`, React will call it when some child component (including distant children) throws an error during rendering. This lets you log that error to an error reporting service in production. +Если вы определите `componentDidCatch`, React вызовет его, когда какой-либо дочерний компонент (включая отдаленные дочерние) вызовет ошибку во время рендеринга. Это позволяет вам регистрировать эту ошибку в службе отчетности об ошибках в продакшене. -Typically, it is used together with [`static getDerivedStateFromError`](#static-getderivedstatefromerror) which lets you update state in response to an error and display an error message to the user. A component with these methods is called an *error boundary.* +Обычно он используется вместе с [`static getDerivedStateFromError`](#static-getderivedstatefromerror), который позволяет обновлять состояние в ответ на ошибку и отображать пользователю сообщение об ошибке. Компонент с этими методами называется *границей ошибок*. -[See an example.](#catching-rendering-errors-with-an-error-boundary) +[См. пример.](#catching-rendering-errors-with-an-error-boundary) -#### Parameters {/*componentdidcatch-parameters*/} +#### Параметры {/*componentdidcatch-parameters*/} -* `error`: The error that was thrown. In practice, it will usually be an instance of [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) but this is not guaranteed because JavaScript allows to [`throw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw) any value, including strings or even `null`. +* `error`: Ошибка, которая была вызвана. На практике это обычно будет экземпляр [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error), но это не гарантируется, поскольку JavaScript позволяет [`throw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw) любое значение, включая строки или даже `null`. -* `info`: An object containing additional information about the error. Its `componentStack` field contains a stack trace with the component that threw, as well as the names and source locations of all its parent components. In production, the component names will be minified. If you set up production error reporting, you can decode the component stack using sourcemaps the same way as you would do for regular JavaScript error stacks. +* `info`: Объект, содержащий дополнительную информацию об ошибке. Его поле `componentStack` содержит трассировку стека с компонентом, который вызвал ошибку, а также имена и исходные расположения всех его родительских компонентов. В продакшене имена компонентов будут минифицированы. Если вы настроили отчетность об ошибках в продакшене, вы можете декодировать стек компонентов с помощью sourcemaps так же, как вы бы сделали для обычных стеков ошибок JavaScript. -#### Returns {/*componentdidcatch-returns*/} +#### Возвращает {/*componentdidcatch-returns*/} -`componentDidCatch` should not return anything. +`componentDidCatch` ничего не должен возвращать. -#### Caveats {/*componentdidcatch-caveats*/} +#### Особенности {/*componentdidcatch-caveats*/} -* In the past, it was common to call `setState` inside `componentDidCatch` in order to update the UI and display the fallback error message. This is deprecated in favor of defining [`static getDerivedStateFromError`.](#static-getderivedstatefromerror) +* В прошлом было принято вызывать `setState` внутри `componentDidCatch` для обновления пользовательского интерфейса и отображения резервного сообщения об ошибке. Это устарело в пользу определения [`static getDerivedStateFromError`.](#static-getderivedstatefromerror) -* Production and development builds of React slightly differ in the way `componentDidCatch` handles errors. In development, the errors will bubble up to `window`, which means that any `window.onerror` or `window.addEventListener('error', callback)` will intercept the errors that have been caught by `componentDidCatch`. In production, instead, the errors will not bubble up, which means any ancestor error handler will only receive errors not explicitly caught by `componentDidCatch`. +* Сборки React для продакшена и разработки немного отличаются в том, как `componentDidCatch` обрабатывает ошибки. В режиме разработки ошибки будут всплывать до `window`, что означает, что любой `window.onerror` или `window.addEventListener('error', callback)` будет перехватывать ошибки, которые были пойманы `componentDidCatch`. В продакшене вместо этого ошибки не будут всплывать, что означает, что любой обработчик ошибок предка получит только ошибки, явно не пойманные `componentDidCatch`. -There is no direct equivalent for `componentDidCatch` in function components yet. If you'd like to avoid creating class components, write a single `ErrorBoundary` component like above and use it throughout your app. Alternatively, you can use the [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) package which does that for you. +Прямого эквивалента для `componentDidCatch` в функциональных компонентах пока нет. Если вы хотите избежать создания классовых компонентов, напишите один компонент `ErrorBoundary`, как показано выше, и используйте его во всем своем приложении. В качестве альтернативы вы можете использовать пакет [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary), который делает это за вас. @@ -236,9 +236,9 @@ There is no direct equivalent for `componentDidCatch` in function components yet ### `componentDidMount()` {/*componentdidmount*/} -If you define the `componentDidMount` method, React will call it when your component is added *(mounted)* to the screen. This is a common place to start data fetching, set up subscriptions, or manipulate the DOM nodes. +Если вы определите метод `componentDidMount`, React вызовет его, когда ваш компонент будет добавлен *(смонтирован)* на экран. Это распространенное место для начала получения данных, настройки подписок или манипулирования DOM-узлами. -If you implement `componentDidMount`, you usually need to implement other lifecycle methods to avoid bugs. For example, if `componentDidMount` reads some state or props, you also have to implement [`componentDidUpdate`](#componentdidupdate) to handle their changes, and [`componentWillUnmount`](#componentwillunmount) to clean up whatever `componentDidMount` was doing. +Если вы реализуете `componentDidMount`, вам обычно нужно реализовать другие методы жизненного цикла, чтобы избежать ошибок. Например, если `componentDidMount` считывает некоторое состояние или пропсы, вам также необходимо реализовать [`componentDidUpdate`](#componentdidupdate) для обработки их изменений и [`componentWillUnmount`](#componentwillunmount) для очистки всего, что делал `componentDidMount`. ```js {6-8} class ChatRoom extends Component { @@ -268,27 +268,27 @@ class ChatRoom extends Component { } ``` -[See more examples.](#adding-lifecycle-methods-to-a-class-component) +[См. больше примеров.](#adding-lifecycle-methods-to-a-class-component) -#### Parameters {/*componentdidmount-parameters*/} +#### Параметры {/*componentdidmount-parameters*/} -`componentDidMount` does not take any parameters. +`componentDidMount` не принимает никаких параметров. -#### Returns {/*componentdidmount-returns*/} +#### Возвращает {/*componentdidmount-returns*/} -`componentDidMount` should not return anything. +`componentDidMount` ничего не должен возвращать. -#### Caveats {/*componentdidmount-caveats*/} +#### Особенности {/*componentdidmount-caveats*/} -- When [Strict Mode](/reference/react/StrictMode) is on, in development React will call `componentDidMount`, then immediately call [`componentWillUnmount`,](#componentwillunmount) and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does. +- Когда включен [Strict Mode](/reference/react/StrictMode), в режиме разработки React вызовет `componentDidMount`, затем немедленно вызовет [`componentWillUnmount`,](#componentwillunmount) а затем снова вызовет `componentDidMount`. Это поможет вам заметить, если вы забыли реализовать `componentWillUnmount` или если его логика не полностью "отражает" то, что делает `componentDidMount`. -- Although you may call [`setState`](#setstate) immediately in `componentDidMount`, it's best to avoid that when you can. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the [`render`](#render) will be called twice in this case, the user won't see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the [`constructor`](#constructor) instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position. +- Хотя вы можете немедленно вызвать [`setState`](#setstate) в `componentDidMount`, лучше избегать этого, когда это возможно. Это вызовет дополнительный рендеринг, но он произойдет до того, как браузер обновит экран. Это гарантирует, что, хотя [`render`](#render) будет вызван дважды в этом случае, пользователь не увидит промежуточное состояние. Используйте этот шаблон с осторожностью, так как он часто вызывает проблемы с производительностью. В большинстве случаев вы можете вместо этого присвоить начальное состояние в [`constructor`](#constructor). Однако это может быть необходимо в случаях, таких как модальные окна и всплывающие подсказки, когда вам нужно измерить DOM-узел перед рендерингом чего-либо, зависящего от его размера или положения. -For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. +Для многих сценариев использования определение `componentDidMount`, `componentDidUpdate` и `componentWillUnmount` вместе в классовых компонентах эквивалентно вызову [`useEffect`](/reference/react/useEffect) в функциональных компонентах. В редких случаях, когда важно, чтобы код выполнялся перед отрисовкой браузера, [`useLayoutEffect`](/reference/react/useLayoutEffect) является более близким аналогом. -[See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) +[См. как выполнить миграцию.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) @@ -296,9 +296,9 @@ For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `com ### `componentDidUpdate(prevProps, prevState, snapshot?)` {/*componentdidupdate*/} -If you define the `componentDidUpdate` method, React will call it immediately after your component has been re-rendered with updated props or state. This method is not called for the initial render. +Если вы определите метод `componentDidUpdate`, React вызовет его сразу после того, как ваш компонент будет повторно отрисован с обновленными пропсами или состоянием. Этот метод не вызывается для начального рендеринга. -You can use it to manipulate the DOM after an update. This is also a common place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed). Typically, you'd use it together with [`componentDidMount`](#componentdidmount) and [`componentWillUnmount`:](#componentwillunmount) +Вы можете использовать его для манипулирования DOM после обновления. Это также распространенное место для выполнения сетевых запросов, при условии, что вы сравниваете текущие пропсы с предыдущими (например, сетевой запрос может быть не нужен, если пропсы не изменились). Обычно вы будете использовать его вместе с [`componentDidMount`](#componentdidmount) и [`componentWillUnmount`:](#componentwillunmount) ```js {10-18} class ChatRoom extends Component { @@ -328,34 +328,34 @@ class ChatRoom extends Component { } ``` -[See more examples.](#adding-lifecycle-methods-to-a-class-component) +[См. больше примеров.](#adding-lifecycle-methods-to-a-class-component) -#### Parameters {/*componentdidupdate-parameters*/} +#### Параметры {/*componentdidupdate-parameters*/} -* `prevProps`: Props before the update. Compare `prevProps` to [`this.props`](#props) to determine what changed. +* `prevProps`: Пропсы до обновления. Сравните `prevProps` с [`this.props`](#props), чтобы определить, что изменилось. -* `prevState`: State before the update. Compare `prevState` to [`this.state`](#state) to determine what changed. +* `prevState`: Состояние до обновления. Сравните `prevState` с [`this.state`](#state), чтобы определить, что изменилось. -* `snapshot`: If you implemented [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate), `snapshot` will contain the value you returned from that method. Otherwise, it will be `undefined`. +* `snapshot`: Если вы реализовали [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate), `snapshot` будет содержать значение, которое вы вернули из этого метода. В противном случае оно будет `undefined`. -#### Returns {/*componentdidupdate-returns*/} +#### Возвращает {/*componentdidupdate-returns*/} -`componentDidUpdate` should not return anything. +`componentDidUpdate` ничего не должен возвращать. -#### Caveats {/*componentdidupdate-caveats*/} +#### Особенности {/*componentdidupdate-caveats*/} -- `componentDidUpdate` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`. +- `componentDidUpdate` не будет вызван, если [`shouldComponentUpdate`](#shouldcomponentupdate) определен и возвращает `false`. -- The logic inside `componentDidUpdate` should usually be wrapped in conditions comparing `this.props` with `prevProps`, and `this.state` with `prevState`. Otherwise, there's a risk of creating infinite loops. +- Логика внутри `componentDidUpdate` обычно должна быть обернута в условия, сравнивающие `this.props` с `prevProps` и `this.state` с `prevState`. В противном случае существует риск создания бесконечных циклов. -- Although you may call [`setState`](#setstate) immediately in `componentDidUpdate`, it's best to avoid that when you can. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the [`render`](#render) will be called twice in this case, the user won't see the intermediate state. This pattern often causes performance issues, but it may be necessary for rare cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position. +- Хотя вы можете немедленно вызвать [`setState`](#setstate) в `componentDidUpdate`, лучше избегать этого, когда это возможно. Это вызовет дополнительный рендеринг, но он произойдет до того, как браузер обновит экран. Это гарантирует, что, хотя [`render`](#render) будет вызван дважды в этом случае, пользователь не увидит промежуточное состояние. Этот шаблон часто вызывает проблемы с производительностью, но он может быть необходим в редких случаях, таких как модальные окна и всплывающие подсказки, когда вам нужно измерить DOM-узел перед рендерингом чего-либо, зависящего от его размера или положения. -For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. +Для многих сценариев использования определение `componentDidMount`, `componentDidUpdate` и `componentWillUnmount` вместе в классовых компонентах эквивалентно вызову [`useEffect`](/reference/react/useEffect) в функциональных компонентах. В редких случаях, когда важно, чтобы код выполнялся перед отрисовкой браузера, [`useLayoutEffect`](/reference/react/useLayoutEffect) является более близким аналогом. -[See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) +[См. как выполнить миграцию.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) --- @@ -364,9 +364,9 @@ For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `com -This API has been renamed from `componentWillMount` to [`UNSAFE_componentWillMount`.](#unsafe_componentwillmount) The old name has been deprecated. In a future major version of React, only the new name will work. +Этот API был переименован из `componentWillMount` в [`UNSAFE_componentWillMount`.](#unsafe_componentwillmount) Старое имя устарело. В будущей основной версии React будет работать только новое имя. -Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components. +Запустите [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles), чтобы автоматически обновить ваши компоненты. @@ -376,9 +376,21 @@ Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-co -This API has been renamed from `componentWillReceiveProps` to [`UNSAFE_componentWillReceiveProps`.](#unsafe_componentwillreceiveprops) The old name has been deprecated. In a future major version of React, only the new name will work. +Этот API был переименован из `componentWillReceiveProps` в [`UNSAFE_componentWillReceiveProps`.](#unsafe_componentwillreceiveprops) Старое имя устарело. В будущей основной версии React будет работать только новое имя. -Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components. +Запустите [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles), чтобы автоматически обновить ваши компоненты. + + + +--- + +### `componentWillReceiveProps(nextProps)` {/*componentwillreceiveprops*/} + + + +Этот API был переименован из `componentWillReceiveProps` в [`UNSAFE_componentWillReceiveProps`.](#unsafe_componentwillreceiveprops) Старое имя устарело. В будущей основной версии React будет работать только новое имя. + +Запустите [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles), чтобы автоматически обновить ваши компоненты. @@ -388,9 +400,9 @@ Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-co -This API has been renamed from `componentWillUpdate` to [`UNSAFE_componentWillUpdate`.](#unsafe_componentwillupdate) The old name has been deprecated. In a future major version of React, only the new name will work. +Этот API был переименован из `componentWillUpdate` в [`UNSAFE_componentWillUpdate`.](#unsafe_componentwillupdate) Старое имя устарело. В будущей основной версии React будет работать только новое имя. -Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components. +Запустите [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles), чтобы автоматически обновить ваши компоненты. @@ -398,9 +410,9 @@ Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-co ### `componentWillUnmount()` {/*componentwillunmount*/} -If you define the `componentWillUnmount` method, React will call it before your component is removed *(unmounted)* from the screen. This is a common place to cancel data fetching or remove subscriptions. +Если вы определите метод `componentWillUnmount`, React вызовет его перед тем, как компонент будет удален *(размонтирован)* с экрана. Это распространенное место для отмены получения данных или удаления подписок. -The logic inside `componentWillUnmount` should "mirror" the logic inside [`componentDidMount`.](#componentdidmount) For example, if `componentDidMount` sets up a subscription, `componentWillUnmount` should clean up that subscription. If the cleanup logic in your `componentWillUnmount` reads some props or state, you will usually also need to implement [`componentDidUpdate`](#componentdidupdate) to clean up resources (such as subscriptions) corresponding to the old props and state. +Логика внутри `componentWillUnmount` должна "отражать" логику внутри [`componentDidMount`.](#componentdidmount) Например, если `componentDidMount` настраивает подписку, `componentWillUnmount` должен очистить эту подписку. Если логика очистки в вашем `componentWillUnmount` читает какие-либо пропсы или состояние, вам обычно также потребуется реализовать [`componentDidUpdate`](#componentdidupdate) для очистки ресурсов (таких как подписки), соответствующих старым пропсам и состоянию. ```js {20-22} class ChatRoom extends Component { @@ -430,25 +442,25 @@ class ChatRoom extends Component { } ``` -[See more examples.](#adding-lifecycle-methods-to-a-class-component) +[См. больше примеров.](#adding-lifecycle-methods-to-a-class-component) -#### Parameters {/*componentwillunmount-parameters*/} +#### Параметры {/*componentwillunmount-parameters*/} -`componentWillUnmount` does not take any parameters. +`componentWillUnmount` не принимает никаких параметров. -#### Returns {/*componentwillunmount-returns*/} +#### Возвращает {/*componentwillunmount-returns*/} -`componentWillUnmount` should not return anything. +`componentWillUnmount` ничего не должен возвращать. -#### Caveats {/*componentwillunmount-caveats*/} +#### Особенности {/*componentwillunmount-caveats*/} -- When [Strict Mode](/reference/react/StrictMode) is on, in development React will call [`componentDidMount`,](#componentdidmount) then immediately call `componentWillUnmount`, and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does. +- Когда [Strict Mode](/reference/react/StrictMode) включен, в режиме разработки React вызовет [`componentDidMount`,](#componentdidmount) затем немедленно вызовет `componentWillUnmount`, а затем снова вызовет `componentDidMount`. Это поможет вам заметить, если вы забыли реализовать `componentWillUnmount` или если его логика не полностью "отражает" то, что делает `componentDidMount`. -For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. +Для многих сценариев использования определение `componentDidMount`, `componentDidUpdate` и `componentWillUnmount` вместе в классовых компонентах эквивалентно вызову [`useEffect`](/reference/react/useEffect) в функциональных компонентах. В редких случаях, когда важно, чтобы код выполнялся перед отрисовкой браузера, [`useLayoutEffect`](/reference/react/useLayoutEffect) является более близким аналогом. -[See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) +[См. как мигрировать.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) @@ -456,27 +468,27 @@ For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `com ### `forceUpdate(callback?)` {/*forceupdate*/} -Forces a component to re-render. +Принудительно перезапускает рендеринг компонента. -Usually, this is not necessary. If your component's [`render`](#render) method only reads from [`this.props`](#props), [`this.state`](#state), or [`this.context`,](#context) it will re-render automatically when you call [`setState`](#setstate) inside your component or one of its parents. However, if your component's `render` method reads directly from an external data source, you have to tell React to update the user interface when that data source changes. That's what `forceUpdate` lets you do. +Обычно это не требуется. Если метод [`render`](#render) вашего компонента только читает из [`this.props`](#props), [`this.state`](#state) или [`this.context`,](#context) он будет автоматически перезапускаться при вызове [`setState`](#setstate) внутри вашего компонента или одного из его родительских компонентов. Однако, если метод `render` вашего компонента читает напрямую из внешнего источника данных, вы должны сообщить React о необходимости обновить пользовательский интерфейс при изменении этого источника данных. Именно это позволяет сделать `forceUpdate`. -Try to avoid all uses of `forceUpdate` and only read from `this.props` and `this.state` in `render`. +Старайтесь избегать всех случаев использования `forceUpdate` и читайте только из `this.props` и `this.state` в `render`. -#### Parameters {/*forceupdate-parameters*/} +#### Параметры {/*forceupdate-parameters*/} -* **optional** `callback` If specified, React will call the `callback` you've provided after the update is committed. +* **необязательный** `callback` Если указан, React вызовет предоставленный вами `callback` после применения обновления. -#### Returns {/*forceupdate-returns*/} +#### Возвращает {/*forceupdate-returns*/} -`forceUpdate` does not return anything. +`forceUpdate` ничего не возвращает. -#### Caveats {/*forceupdate-caveats*/} +#### Особенности {/*forceupdate-caveats*/} -- If you call `forceUpdate`, React will re-render without calling [`shouldComponentUpdate`.](#shouldcomponentupdate) +- Если вы вызовете `forceUpdate`, React перезапустит рендеринг без вызова [`shouldComponentUpdate`.](#shouldcomponentupdate) -Reading an external data source and forcing class components to re-render in response to its changes with `forceUpdate` has been superseded by [`useSyncExternalStore`](/reference/react/useSyncExternalStore) in function components. +Чтение внешнего источника данных и принудительный перезапуск рендеринга классовых компонентов в ответ на его изменения с помощью `forceUpdate` было заменено [`useSyncExternalStore`](/reference/react/useSyncExternalStore) в функциональных компонентах. @@ -484,9 +496,9 @@ Reading an external data source and forcing class components to re-render in res ### `getSnapshotBeforeUpdate(prevProps, prevState)` {/*getsnapshotbeforeupdate*/} -If you implement `getSnapshotBeforeUpdate`, React will call it immediately before React updates the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed. Any value returned by this lifecycle method will be passed as a parameter to [`componentDidUpdate`.](#componentdidupdate) +Если вы реализуете `getSnapshotBeforeUpdate`, React вызовет его непосредственно перед тем, как React обновит DOM. Это позволяет вашему компоненту получить некоторую информацию из DOM (например, положение прокрутки) до того, как она может быть изменена. Любое значение, возвращенное этим методом жизненного цикла, будет передано в качестве параметра в [`componentDidUpdate`.](#componentdidupdate) -For example, you can use it in a UI like a chat thread that needs to preserve its scroll position during updates: +Например, вы можете использовать его в пользовательском интерфейсе, таком как чат, который должен сохранять положение прокрутки во время обновлений: ```js {7-15,17} class ScrollingList extends React.Component { @@ -496,8 +508,8 @@ class ScrollingList extends React.Component { } getSnapshotBeforeUpdate(prevProps, prevState) { - // Are we adding new items to the list? - // Capture the scroll position so we can adjust scroll later. + // Добавляем ли мы новые элементы в список? + // Захватываем положение прокрутки, чтобы мы могли настроить его позже. if (prevProps.list.length < this.props.list.length) { const list = this.listRef.current; return list.scrollHeight - list.scrollTop; @@ -506,9 +518,9 @@ class ScrollingList extends React.Component { } componentDidUpdate(prevProps, prevState, snapshot) { - // If we have a snapshot value, we've just added new items. - // Adjust scroll so these new items don't push the old ones out of view. - // (snapshot here is the value returned from getSnapshotBeforeUpdate) + // Если у нас есть значение снимка, мы только что добавили новые элементы. + // Настраиваем прокрутку, чтобы эти новые элементы не вытесняли старые из поля зрения. + // (snapshot здесь — это значение, возвращенное из getSnapshotBeforeUpdate) if (snapshot !== null) { const list = this.listRef.current; list.scrollTop = list.scrollHeight - snapshot; @@ -517,31 +529,31 @@ class ScrollingList extends React.Component { render() { return ( -
{/* ...contents... */}
+
{/* ...содержимое... */}
); } } ``` -In the above example, it is important to read the `scrollHeight` property directly in `getSnapshotBeforeUpdate`. It is not safe to read it in [`render`](#render), [`UNSAFE_componentWillReceiveProps`](#unsafe_componentwillreceiveprops), or [`UNSAFE_componentWillUpdate`](#unsafe_componentwillupdate) because there is a potential time gap between these methods getting called and React updating the DOM. +В приведенном выше примере важно считывать свойство `scrollHeight` непосредственно в `getSnapshotBeforeUpdate`. Небезопасно считывать его в [`render`](#render), [`UNSAFE_componentWillReceiveProps`](#unsafe_componentwillreceiveprops) или [`UNSAFE_componentWillUpdate`](#unsafe_componentwillupdate), поскольку существует потенциальный временной разрыв между вызовом этих методов и обновлением DOM в React. -#### Parameters {/*getsnapshotbeforeupdate-parameters*/} +#### Параметры {/*getsnapshotbeforeupdate-parameters*/} -* `prevProps`: Props before the update. Compare `prevProps` to [`this.props`](#props) to determine what changed. +* `prevProps`: Пропсы до обновления. Сравните `prevProps` с [`this.props`](#props), чтобы определить, что изменилось. -* `prevState`: State before the update. Compare `prevState` to [`this.state`](#state) to determine what changed. +* `prevState`: Состояние до обновления. Сравните `prevState` с [`this.state`](#state), чтобы определить, что изменилось. -#### Returns {/*getsnapshotbeforeupdate-returns*/} +#### Возвращает {/*getsnapshotbeforeupdate-returns*/} -You should return a snapshot value of any type that you'd like, or `null`. The value you returned will be passed as the third argument to [`componentDidUpdate`.](#componentdidupdate) +Вы должны вернуть значение снимка любого типа, которое вы хотите, или `null`. Возвращенное вами значение будет передано в качестве третьего аргумента в [`componentDidUpdate`.](#componentdidupdate) -#### Caveats {/*getsnapshotbeforeupdate-caveats*/} +#### Особенности {/*getsnapshotbeforeupdate-caveats*/} -- `getSnapshotBeforeUpdate` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`. +- `getSnapshotBeforeUpdate` не будет вызван, если [`shouldComponentUpdate`](#shouldcomponentupdate) определен и возвращает `false`. -At the moment, there is no equivalent to `getSnapshotBeforeUpdate` for function components. This use case is very uncommon, but if you have the need for it, for now you'll have to write a class component. +В настоящее время эквивалента `getSnapshotBeforeUpdate` для функциональных компонентов нет. Этот сценарий использования очень редок, но если он вам нужен, пока вам придется написать классовый компонент. @@ -549,9 +561,9 @@ At the moment, there is no equivalent to `getSnapshotBeforeUpdate` for function ### `render()` {/*render*/} -The `render` method is the only required method in a class component. +Метод `render` является единственным обязательным методом в классовом компоненте. -The `render` method should specify what you want to appear on the screen, for example: +Метод `render` должен указывать, что вы хотите отобразить на экране, например: ```js {4-6} import { Component } from 'react'; @@ -563,33 +575,33 @@ class Greeting extends Component { } ``` -React may call `render` at any moment, so you shouldn't assume that it runs at a particular time. Usually, the `render` method should return a piece of [JSX](/learn/writing-markup-with-jsx), but a few [other return types](#render-returns) (like strings) are supported. To calculate the returned JSX, the `render` method can read [`this.props`](#props), [`this.state`](#state), and [`this.context`](#context). +React может вызвать `render` в любой момент, поэтому не следует предполагать, что он выполняется в определенное время. Обычно метод `render` должен возвращать фрагмент [JSX](/learn/writing-markup-with-jsx), но поддерживается несколько [других типов возвращаемых значений](#render-returns) (например, строки). Для расчета возвращаемого JSX метод `render` может читать [`this.props`](#props), [`this.state`](#state) и [`this.context`.](#context) -You should write the `render` method as a pure function, meaning that it should return the same result if props, state, and context are the same. It also shouldn't contain side effects (like setting up subscriptions) or interact with the browser APIs. Side effects should happen either in event handlers or methods like [`componentDidMount`.](#componentdidmount) +Вы должны писать метод `render` как чистую функцию, то есть он должен возвращать один и тот же результат, если пропсы, состояние и контекст одинаковы. Он также не должен содержать побочных эффектов (например, настройку подписок) или взаимодействовать с API браузера. Побочные эффекты должны происходить либо в обработчиках событий, либо в методах, таких как [`componentDidMount`.](#componentdidmount) -#### Parameters {/*render-parameters*/} +#### Параметры {/*render-parameters*/} -`render` does not take any parameters. +`render` не принимает никаких параметров. -#### Returns {/*render-returns*/} +#### Возвращает {/*render-returns*/} -`render` can return any valid React node. This includes React elements such as `
`, strings, numbers, [portals](/reference/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes. +`render` может возвращать любой допустимый React-узел. Это включает React-элементы, такие как `
`, строки, числа, [порталы](/reference/react-dom/createPortal), пустые узлы (`null`, `undefined`, `true` и `false`), а также массивы React-узлов. -#### Caveats {/*render-caveats*/} +#### Особенности {/*render-caveats*/} -- `render` should be written as a pure function of props, state, and context. It should not have side effects. +- `render` должен быть написан как чистая функция от пропсов, состояния и контекста. Он не должен иметь побочных эффектов. -- `render` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`. +- `render` не будет вызван, если [`shouldComponentUpdate`](#shouldcomponentupdate) определен и возвращает `false`. -- When [Strict Mode](/reference/react/StrictMode) is on, React will call `render` twice in development and then throw away one of the results. This helps you notice the accidental side effects that need to be moved out of the `render` method. +- Когда [Strict Mode](/reference/react/StrictMode) включен, React вызовет `render` дважды в режиме разработки, а затем отбросит один из результатов. Это поможет вам заметить случайные побочные эффекты, которые необходимо вынести из метода `render`. -- There is no one-to-one correspondence between the `render` call and the subsequent `componentDidMount` or `componentDidUpdate` call. Some of the `render` call results may be discarded by React when it's beneficial. +- Нет однозначного соответствия между вызовом `render` и последующим вызовом `componentDidMount` или `componentDidUpdate`. Некоторые результаты вызова `render` могут быть отброшены React, когда это выгодно. --- ### `setState(nextState, callback?)` {/*setstate*/} -Call `setState` to update the state of your React component. +Вызовите `setState`, чтобы обновить состояние вашего React-компонента. ```js {8-10} class Form extends Component { @@ -615,11 +627,11 @@ class Form extends Component { } ``` -`setState` enqueues changes to the component state. It tells React that this component and its children need to re-render with the new state. This is the main way you'll update the user interface in response to interactions. +`setState` ставит в очередь изменения состояния компонента. Он сообщает React, что этот компонент и его дочерние компоненты должны быть перерисованы с новым состоянием. Это основной способ обновления пользовательского интерфейса в ответ на взаимодействие. -Calling `setState` **does not** change the current state in the already executing code: +Вызов `setState` **не** изменяет текущее состояние в уже выполняющемся коде: ```js {6} function handleClick() { @@ -627,15 +639,15 @@ function handleClick() { this.setState({ name: 'Robin' }); - console.log(this.state.name); // Still "Taylor"! + console.log(this.state.name); // Все еще "Taylor"! } ``` -It only affects what `this.state` will return starting from the *next* render. +Это влияет только на то, что `this.state` вернет начиная со *следующего* рендеринга. -You can also pass a function to `setState`. It lets you update state based on the previous state: +Вы также можете передать функцию в `setState`. Это позволит вам обновлять состояние на основе предыдущего состояния: ```js {2-6} handleIncreaseAge = () => { @@ -647,31 +659,31 @@ You can also pass a function to `setState`. It lets you update state based on th } ``` -You don't have to do this, but it's handy if you want to update state multiple times during the same event. +Вам не обязательно это делать, но это удобно, если вы хотите обновить состояние несколько раз во время одного события. -#### Parameters {/*setstate-parameters*/} +#### Параметры {/*setstate-parameters*/} -* `nextState`: Either an object or a function. - * If you pass an object as `nextState`, it will be shallowly merged into `this.state`. - * If you pass a function as `nextState`, it will be treated as an _updater function_. It must be pure, should take the pending state and props as arguments, and should return the object to be shallowly merged into `this.state`. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state. +* `nextState`: Объект или функция. + * Если вы передаете объект в качестве `nextState`, он будет поверхностно объединен с `this.state`. + * Если вы передаете функцию в качестве `nextState`, она будет рассматриваться как _функция обновления_. Она должна быть чистой, принимать ожидаемое состояние и пропсы в качестве аргументов и возвращать объект для поверхностного объединения с `this.state`. React поместит вашу функцию обновления в очередь и перезапустит рендеринг вашего компонента. Во время следующего рендеринга React рассчитает следующее состояние, применив все поставленные в очередь обработчики к предыдущему состоянию. -* **optional** `callback`: If specified, React will call the `callback` you've provided after the update is committed. +* **необязательный** `callback`: Если указан, React вызовет предоставленный вами `callback` после применения обновления. -#### Returns {/*setstate-returns*/} +#### Возвращает {/*setstate-returns*/} -`setState` does not return anything. +`setState` ничего не возвращает. -#### Caveats {/*setstate-caveats*/} +#### Особенности {/*setstate-caveats*/} -- Think of `setState` as a *request* rather than an immediate command to update the component. When multiple components update their state in response to an event, React will batch their updates and re-render them together in a single pass at the end of the event. In the rare case that you need to force a particular state update to be applied synchronously, you may wrap it in [`flushSync`,](/reference/react-dom/flushSync) but this may hurt performance. +- Думайте о `setState` как о *запросе*, а не как о немедленной команде на обновление компонента. Когда несколько компонентов обновляют свое состояние в ответ на событие, React будет группировать их обновления и перерисовывать их вместе за один проход в конце события. В редких случаях, когда вам нужно принудительно применить определенное обновление состояния синхронно, вы можете обернуть его в [`flushSync`,](/reference/react-dom/flushSync), но это может снизить производительность. -- `setState` does not update `this.state` immediately. This makes reading `this.state` right after calling `setState` a potential pitfall. Instead, use [`componentDidUpdate`](#componentdidupdate) or the setState `callback` argument, either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, you can pass a function to `nextState` as described above. +- `setState` не обновляет `this.state` немедленно. Это делает чтение `this.state` сразу после вызова `setState` потенциальной проблемой. Вместо этого используйте [`componentDidUpdate`](#componentdidupdate) или аргумент `callback` setState, оба из которых гарантированно сработают после применения обновления. Если вам нужно установить состояние на основе предыдущего состояния, вы можете передать функцию в `nextState`, как описано выше. -Calling `setState` in class components is similar to calling a [`set` function](/reference/react/useState#setstate) in function components. +Вызов `setState` в классовых компонентах аналогичен вызову [`set` функции](/reference/react/useState#setstate) в функциональных компонентах. -[See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function) +[См. как мигрировать.](#migrating-a-component-with-state-from-a-class-to-a-function) @@ -679,9 +691,9 @@ Calling `setState` in class components is similar to calling a [`set` function]( ### `shouldComponentUpdate(nextProps, nextState, nextContext)` {/*shouldcomponentupdate*/} -If you define `shouldComponentUpdate`, React will call it to determine whether a re-render can be skipped. +Если вы определите `shouldComponentUpdate`, React вызовет её, чтобы определить, можно ли пропустить повторный рендеринг. -If you are confident you want to write it by hand, you may compare `this.props` with `nextProps` and `this.state` with `nextState` and return `false` to tell React the update can be skipped. +Если вы уверены, что хотите написать её вручную, вы можете сравнить `this.props` с `nextProps` и `this.state` с `nextState` и вернуть `false`, чтобы сообщить React, что обновление можно пропустить. ```js {6-18} class Rectangle extends Component { @@ -697,7 +709,7 @@ class Rectangle extends Component { nextProps.size.height === this.props.size.height && nextState.isHovered === this.state.isHovered ) { - // Nothing has changed, so a re-render is unnecessary + // Ничего не изменилось, поэтому повторный рендеринг не требуется return false; } return true; @@ -708,35 +720,35 @@ class Rectangle extends Component { ``` -React calls `shouldComponentUpdate` before rendering when new props or state are being received. Defaults to `true`. This method is not called for the initial render or when [`forceUpdate`](#forceupdate) is used. +React вызывает `shouldComponentUpdate` перед рендерингом, когда получены новые пропсы или состояние. По умолчанию возвращает `true`. Этот метод не вызывается при начальном рендеринге или при использовании [`forceUpdate`](#forceupdate). -#### Parameters {/*shouldcomponentupdate-parameters*/} +#### Параметры {/*shouldcomponentupdate-parameters*/} -- `nextProps`: The next props that the component is about to render with. Compare `nextProps` to [`this.props`](#props) to determine what changed. -- `nextState`: The next state that the component is about to render with. Compare `nextState` to [`this.state`](#props) to determine what changed. -- `nextContext`: The next context that the component is about to render with. Compare `nextContext` to [`this.context`](#context) to determine what changed. Only available if you specify [`static contextType`](#static-contexttype). +- `nextProps`: Следующие пропсы, с которыми компонент собирается отрендериться. Сравните `nextProps` с [`this.props`](#props), чтобы определить, что изменилось. +- `nextState`: Следующее состояние, с которым компонент собирается отрендериться. Сравните `nextState` с [`this.state`](#props), чтобы определить, что изменилось. +- `nextContext`: Следующий контекст, который компонент собирается получить от ближайшего провайдера. Сравните `nextContext` с [`this.context`](#context), чтобы определить, что изменилось. Доступно только если вы указали [`static contextType`](#static-contexttype). -#### Returns {/*shouldcomponentupdate-returns*/} +#### Возвращаемое значение {/*shouldcomponentupdate-returns*/} -Return `true` if you want the component to re-render. That's the default behavior. +Верните `true`, если вы хотите, чтобы компонент повторно отрендерился. Это поведение по умолчанию. -Return `false` to tell React that re-rendering can be skipped. +Верните `false`, чтобы сообщить React, что повторный рендеринг можно пропустить. -#### Caveats {/*shouldcomponentupdate-caveats*/} +#### Предостережения {/*shouldcomponentupdate-caveats*/} -- This method *only* exists as a performance optimization. If your component breaks without it, fix that first. +- Этот метод существует *только* как оптимизация производительности. Если ваш компонент ломается без него, сначала исправьте это. -- Consider using [`PureComponent`](/reference/react/PureComponent) instead of writing `shouldComponentUpdate` by hand. `PureComponent` shallowly compares props and state, and reduces the chance that you'll skip a necessary update. +- Рассмотрите возможность использования [`PureComponent`](/reference/react/PureComponent) вместо ручного написания `shouldComponentUpdate`. `PureComponent` выполняет поверхностное сравнение пропсов и состояния, уменьшая вероятность пропуска необходимого обновления. -- We do not recommend doing deep equality checks or using `JSON.stringify` in `shouldComponentUpdate`. It makes performance unpredictable and dependent on the data structure of every prop and state. In the best case, you risk introducing multi-second stalls to your application, and in the worst case you risk crashing it. +- Мы не рекомендуем выполнять глубокие проверки равенства или использовать `JSON.stringify` в `shouldComponentUpdate`. Это делает производительность непредсказуемой и зависимой от структуры данных каждого пропа и состояния. В лучшем случае вы рискуете ввести задержки в несколько секунд в ваше приложение, а в худшем — вызвать его сбой. -- Returning `false` does not prevent child components from re-rendering when *their* state changes. +- Возврат `false` не предотвращает повторный рендеринг дочерних компонентов, когда изменяется *их* состояние. -- Returning `false` does not *guarantee* that the component will not re-render. React will use the return value as a hint but it may still choose to re-render your component if it makes sense to do for other reasons. +- Возврат `false` не *гарантирует*, что компонент не будет повторно отрендерен. React будет использовать возвращаемое значение как подсказку, но может все же выбрать повторный рендеринг вашего компонента, если это имеет смысл по другим причинам. -Optimizing class components with `shouldComponentUpdate` is similar to optimizing function components with [`memo`.](/reference/react/memo) Function components also offer more granular optimization with [`useMemo`.](/reference/react/useMemo) +Оптимизация классовых компонентов с помощью `shouldComponentUpdate` похожа на оптимизацию функциональных компонентов с помощью [`memo`.](/reference/react/memo) Функциональные компоненты также предлагают более детальную оптимизацию с помощью [`useMemo`.](/reference/react/useMemo) @@ -744,32 +756,32 @@ Optimizing class components with `shouldComponentUpdate` is similar to optimizin ### `UNSAFE_componentWillMount()` {/*unsafe_componentwillmount*/} -If you define `UNSAFE_componentWillMount`, React will call it immediately after the [`constructor`.](#constructor) It only exists for historical reasons and should not be used in any new code. Instead, use one of the alternatives: +Если вы определите `UNSAFE_componentWillMount`, React вызовет её сразу после [`constructor`.](#constructor) Она существует только по историческим причинам и не должна использоваться в новом коде. Вместо этого используйте одну из альтернатив: -- To initialize state, declare [`state`](#state) as a class field or set `this.state` inside the [`constructor`.](#constructor) -- If you need to run a side effect or set up a subscription, move that logic to [`componentDidMount`](#componentdidmount) instead. +- Для инициализации состояния объявите [`state`](#state) как поле класса или установите `this.state` внутри [`constructor`.](#constructor) +- Если вам нужно выполнить побочный эффект или настроить подписку, переместите эту логику в [`componentDidMount`](#componentdidmount) вместо этого. -[See examples of migrating away from unsafe lifecycles.](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#examples) +[Примеры миграции с устаревших жизненных циклов.](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#examples) -#### Parameters {/*unsafe_componentwillmount-parameters*/} +#### Параметры {/*unsafe_componentwillmount-parameters*/} -`UNSAFE_componentWillMount` does not take any parameters. +`UNSAFE_componentWillMount` не принимает никаких параметров. -#### Returns {/*unsafe_componentwillmount-returns*/} +#### Возвращаемое значение {/*unsafe_componentwillmount-returns*/} -`UNSAFE_componentWillMount` should not return anything. +`UNSAFE_componentWillMount` не должна ничего возвращать. -#### Caveats {/*unsafe_componentwillmount-caveats*/} +#### Предостережения {/*unsafe_componentwillmount-caveats*/} -- `UNSAFE_componentWillMount` will not get called if the component implements [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) or [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate) +- `UNSAFE_componentWillMount` не будет вызвана, если компонент реализует [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) или [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate) -- Despite its naming, `UNSAFE_componentWillMount` does not guarantee that the component *will* get mounted if your app uses modern React features like [`Suspense`.](/reference/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. This is why this method is "unsafe". Code that relies on mounting (like adding a subscription) should go into [`componentDidMount`.](#componentdidmount) +- Несмотря на своё название, `UNSAFE_componentWillMount` не гарантирует, что компонент *будет* смонтирован, если ваше приложение использует современные возможности React, такие как [`Suspense`.](/reference/react/Suspense) Если попытка рендеринга приостановлена (например, потому что код какого-либо дочернего компонента ещё не загружен), React отбросит текущее дерево и попытается сконструировать компонент с нуля во время следующей попытки. Именно поэтому этот метод является "небезопасным". Код, который полагается на монтирование (например, добавление подписки), должен быть помещён в [`componentDidMount`.](#componentdidmount) -- `UNSAFE_componentWillMount` is the only lifecycle method that runs during [server rendering.](/reference/react-dom/server) For all practical purposes, it is identical to [`constructor`,](#constructor) so you should use the `constructor` for this type of logic instead. +- `UNSAFE_componentWillMount` — единственный метод жизненного цикла, который выполняется во время [серверного рендеринга.](/reference/react-dom/server) Для всех практических целей он идентичен [`constructor`,](#constructor) поэтому для такого типа логики следует использовать `constructor`. -Calling [`setState`](#setstate) inside `UNSAFE_componentWillMount` in a class component to initialize state is equivalent to passing that state as the initial state to [`useState`](/reference/react/useState) in a function component. +Вызов [`setState`](#setstate) внутри `UNSAFE_componentWillMount` в классовом компоненте для инициализации состояния эквивалентен передаче этого состояния в качестве начального состояния в [`useState`](/reference/react/useState) в функциональном компоненте. @@ -777,37 +789,37 @@ Calling [`setState`](#setstate) inside `UNSAFE_componentWillMount` in a class co ### `UNSAFE_componentWillReceiveProps(nextProps, nextContext)` {/*unsafe_componentwillreceiveprops*/} -If you define `UNSAFE_componentWillReceiveProps`, React will call it when the component receives new props. It only exists for historical reasons and should not be used in any new code. Instead, use one of the alternatives: +Если вы определите `UNSAFE_componentWillReceiveProps`, React вызовет её при получении компонентом новых пропсов. Она существует только по историческим причинам и не должна использоваться в новом коде. Вместо этого используйте одну из альтернатив: -- If you need to **run a side effect** (for example, fetch data, run an animation, or reinitialize a subscription) in response to prop changes, move that logic to [`componentDidUpdate`](#componentdidupdate) instead. -- If you need to **avoid re-computing some data only when a prop changes,** use a [memoization helper](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization) instead. -- If you need to **"reset" some state when a prop changes,** consider either making a component [fully controlled](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) or [fully uncontrolled with a key](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) instead. -- If you need to **"adjust" some state when a prop changes,** check whether you can compute all the necessary information from props alone during rendering. If you can't, use [`static getDerivedStateFromProps`](/reference/react/Component#static-getderivedstatefromprops) instead. +- Если вам нужно **выполнить побочный эффект** (например, получить данные, запустить анимацию или переинициализировать подписку) в ответ на изменения пропсов, переместите эту логику в [`componentDidUpdate`](#componentdidupdate) вместо этого. +- Если вам нужно **избежать повторного вычисления некоторых данных только при изменении пропа,** вместо этого используйте [вспомогательный метод мемоизации](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization). +- Если вам нужно **"сбросить" некоторое состояние при изменении пропа,** рассмотрите возможность сделать компонент [полностью управляемым](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) или [полностью неуправляемым с ключом](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) вместо этого. +- Если вам нужно **"скорректировать" некоторое состояние при изменении пропа,** проверьте, можете ли вы вычислить всю необходимую информацию только из пропсов во время рендеринга. Если не можете, вместо этого используйте [`static getDerivedStateFromProps`](/reference/react/Component#static-getderivedstatefromprops). -[See examples of migrating away from unsafe lifecycles.](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props) +[Примеры миграции с устаревших жизненных циклов.](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props) -#### Parameters {/*unsafe_componentwillreceiveprops-parameters*/} +#### Параметры {/*unsafe_componentwillreceiveprops-parameters*/} -- `nextProps`: The next props that the component is about to receive from its parent component. Compare `nextProps` to [`this.props`](#props) to determine what changed. -- `nextContext`: The next context that the component is about to receive from the closest provider. Compare `nextContext` to [`this.context`](#context) to determine what changed. Only available if you specify [`static contextType`](#static-contexttype). +- `nextProps`: Следующие пропсы, которые компонент собирается получить от родительского компонента. Сравните `nextProps` с [`this.props`](#props), чтобы определить, что изменилось. +- `nextContext`: Следующий контекст, который компонент собирается получить от ближайшего провайдера. Сравните `nextContext` с [`this.context`](#context), чтобы определить, что изменилось. Доступно только если вы указали [`static contextType`](#static-contexttype). -#### Returns {/*unsafe_componentwillreceiveprops-returns*/} +#### Возвращаемое значение {/*unsafe_componentwillreceiveprops-returns*/} -`UNSAFE_componentWillReceiveProps` should not return anything. +`UNSAFE_componentWillReceiveProps` не должна ничего возвращать. -#### Caveats {/*unsafe_componentwillreceiveprops-caveats*/} +#### Предостережения {/*unsafe_componentwillreceiveprops-caveats*/} -- `UNSAFE_componentWillReceiveProps` will not get called if the component implements [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) or [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate) +- `UNSAFE_componentWillReceiveProps` не будет вызвана, если компонент реализует [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) или [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate) -- Despite its naming, `UNSAFE_componentWillReceiveProps` does not guarantee that the component *will* receive those props if your app uses modern React features like [`Suspense`.](/reference/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. By the time of the next render attempt, the props might be different. This is why this method is "unsafe". Code that should run only for committed updates (like resetting a subscription) should go into [`componentDidUpdate`.](#componentdidupdate) +- Несмотря на своё название, `UNSAFE_componentWillReceiveProps` не гарантирует, что компонент *получит* эти пропсы, если ваше приложение использует современные возможности React, такие как [`Suspense`.](/reference/react/Suspense) Если попытка рендеринга приостановлена (например, потому что код какого-либо дочернего компонента ещё не загружен), React отбросит текущее дерево и попытается сконструировать компонент с нуля во время следующей попытки. К моменту следующей попытки рендеринга пропсы могут измениться. Именно поэтому этот метод является "небезопасным". Код, который должен выполняться только для зафиксированных обновлений (например, сброс подписки), должен быть помещён в [`componentDidUpdate`.](#componentdidupdate) -- `UNSAFE_componentWillReceiveProps` does not mean that the component has received *different* props than the last time. You need to compare `nextProps` and `this.props` yourself to check if something changed. +- `UNSAFE_componentWillReceiveProps` не означает, что компонент получил *другие* пропсы, чем в прошлый раз. Вам нужно самостоятельно сравнить `nextProps` и `this.props`, чтобы проверить, изменилось ли что-то. -- React doesn't call `UNSAFE_componentWillReceiveProps` with initial props during mounting. It only calls this method if some of component's props are going to be updated. For example, calling [`setState`](#setstate) doesn't generally trigger `UNSAFE_componentWillReceiveProps` inside the same component. +- React не вызывает `UNSAFE_componentWillReceiveProps` с начальными пропсами во время монтирования. Он вызывает этот метод только в том случае, если некоторые пропсы компонента будут обновлены. Например, вызов [`setState`](#setstate) обычно не запускает `UNSAFE_componentWillReceiveProps` внутри того же компонента. -Calling [`setState`](#setstate) inside `UNSAFE_componentWillReceiveProps` in a class component to "adjust" state is equivalent to [calling the `set` function from `useState` during rendering](/reference/react/useState#storing-information-from-previous-renders) in a function component. +Вызов [`setState`](#setstate) внутри `UNSAFE_componentWillReceiveProps` в классовом компоненте для "корректировки" состояния эквивалентен [вызову функции `set` из `useState` во время рендеринга](/reference/react/useState#storing-information-from-previous-renders) в функциональном компоненте. @@ -816,39 +828,39 @@ Calling [`setState`](#setstate) inside `UNSAFE_componentWillReceiveProps` in a c ### `UNSAFE_componentWillUpdate(nextProps, nextState)` {/*unsafe_componentwillupdate*/} -If you define `UNSAFE_componentWillUpdate`, React will call it before rendering with the new props or state. It only exists for historical reasons and should not be used in any new code. Instead, use one of the alternatives: +Если вы определите `UNSAFE_componentWillUpdate`, React вызовет её перед рендерингом с новыми пропсами или состоянием. Она существует только по историческим причинам и не должна использоваться в новом коде. Вместо этого используйте одну из альтернатив: -- If you need to run a side effect (for example, fetch data, run an animation, or reinitialize a subscription) in response to prop or state changes, move that logic to [`componentDidUpdate`](#componentdidupdate) instead. -- If you need to read some information from the DOM (for example, to save the current scroll position) so that you can use it in [`componentDidUpdate`](#componentdidupdate) later, read it inside [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate) instead. +- Если вам нужно выполнить побочный эффект (например, получить данные, запустить анимацию или переинициализировать подписку) в ответ на изменения пропсов или состояния, переместите эту логику в [`componentDidUpdate`](#componentdidupdate) вместо этого. +- Если вам нужно прочитать некоторую информацию из DOM (например, чтобы сохранить текущую позицию прокрутки), чтобы использовать её позже в [`componentDidUpdate`](#componentdidupdate), прочитайте её внутри [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate) вместо этого. -[See examples of migrating away from unsafe lifecycles.](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#examples) +[Примеры миграции с устаревших жизненных циклов.](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#examples) -#### Parameters {/*unsafe_componentwillupdate-parameters*/} +#### Параметры {/*unsafe_componentwillupdate-parameters*/} -- `nextProps`: The next props that the component is about to render with. Compare `nextProps` to [`this.props`](#props) to determine what changed. -- `nextState`: The next state that the component is about to render with. Compare `nextState` to [`this.state`](#state) to determine what changed. +- `nextProps`: Следующие пропсы, с которыми компонент собирается отрендериться. Сравните `nextProps` с [`this.props`](#props), чтобы определить, что изменилось. +- `nextState`: Следующее состояние, с которым компонент собирается отрендериться. Сравните `nextState` с [`this.state`](#state), чтобы определить, что изменилось. -#### Returns {/*unsafe_componentwillupdate-returns*/} +#### Возвращаемое значение {/*unsafe_componentwillupdate-returns*/} -`UNSAFE_componentWillUpdate` should not return anything. +`UNSAFE_componentWillUpdate` не должна ничего возвращать. -#### Caveats {/*unsafe_componentwillupdate-caveats*/} +#### Предостережения {/*unsafe_componentwillupdate-caveats*/} -- `UNSAFE_componentWillUpdate` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`. +- `UNSAFE_componentWillUpdate` не будет вызвана, если определён [`shouldComponentUpdate`](#shouldcomponentupdate) и он возвращает `false`. -- `UNSAFE_componentWillUpdate` will not get called if the component implements [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) or [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate) +- `UNSAFE_componentWillUpdate` не будет вызвана, если компонент реализует [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) или [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate) -- It's not supported to call [`setState`](#setstate) (or any method that leads to `setState` being called, like dispatching a Redux action) during `componentWillUpdate`. +- Вызов [`setState`](#setstate) (или любого метода, который приводит к вызову `setState`, например, диспетчеризация действия Redux) во время `componentWillUpdate` не поддерживается. -- Despite its naming, `UNSAFE_componentWillUpdate` does not guarantee that the component *will* update if your app uses modern React features like [`Suspense`.](/reference/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. By the time of the next render attempt, the props and state might be different. This is why this method is "unsafe". Code that should run only for committed updates (like resetting a subscription) should go into [`componentDidUpdate`.](#componentdidupdate) +- Несмотря на своё название, `UNSAFE_componentWillUpdate` не гарантирует, что компонент *обновится*, если ваше приложение использует современные возможности React, такие как [`Suspense`.](/reference/react/Suspense) Если попытка рендеринга приостановлена (например, потому что код какого-либо дочернего компонента ещё не загружен), React отбросит текущее дерево и попытается сконструировать компонент с нуля во время следующей попытки. К моменту следующей попытки рендеринга пропсы и состояние могут измениться. Именно поэтому этот метод является "небезопасным". Код, который должен выполняться только для зафиксированных обновлений (например, сброс подписки), должен быть помещён в [`componentDidUpdate`.](#componentdidupdate) -- `UNSAFE_componentWillUpdate` does not mean that the component has received *different* props or state than the last time. You need to compare `nextProps` with `this.props` and `nextState` with `this.state` yourself to check if something changed. +- `UNSAFE_componentWillUpdate` не означает, что компонент получил *другие* пропсы или состояние, чем в прошлый раз. Вам нужно самостоятельно сравнить `nextProps` с `this.props` и `nextState` с `this.state`, чтобы проверить, изменилось ли что-то. -- React doesn't call `UNSAFE_componentWillUpdate` with initial props and state during mounting. +- React не вызывает `UNSAFE_componentWillUpdate` с начальными пропсами и состоянием во время монтирования. -There is no direct equivalent to `UNSAFE_componentWillUpdate` in function components. +Прямого эквивалента `UNSAFE_componentWillUpdate` в функциональных компонентах нет. @@ -856,7 +868,7 @@ There is no direct equivalent to `UNSAFE_componentWillUpdate` in function compon ### `static contextType` {/*static-contexttype*/} -If you want to read [`this.context`](#context-instance-field) from your class component, you must specify which context it needs to read. The context you specify as the `static contextType` must be a value previously created by [`createContext`.](/reference/react/createContext) +Если вы хотите читать [`this.context`](#context-instance-field) из вашего классового компонента, вы должны указать, какой контекст ему необходимо читать. Контекст, который вы указываете как `static contextType`, должен быть значением, ранее созданным с помощью [`createContext`.](/reference/react/createContext) ```js {2} class Button extends Component { @@ -876,9 +888,9 @@ class Button extends Component { -Reading `this.context` in class components is equivalent to [`useContext`](/reference/react/useContext) in function components. +Чтение `this.context` в классовых компонентах эквивалентно [`useContext`](/reference/react/useContext) в функциональных компонентах. -[See how to migrate.](#migrating-a-component-with-context-from-a-class-to-a-function) +[Как мигрировать.](#migrating-a-component-with-context-from-a-class-to-a-function) @@ -886,9 +898,9 @@ Reading `this.context` in class components is equivalent to [`useContext`](/refe ### `static defaultProps` {/*static-defaultprops*/} -You can define `static defaultProps` to set the default props for the class. They will be used for `undefined` and missing props, but not for `null` props. +Вы можете определить `static defaultProps`, чтобы установить значения пропсов по умолчанию для класса. Они будут использоваться для `undefined` и отсутствующих пропсов, но не для `null` пропсов. -For example, here is how you define that the `color` prop should default to `'blue'`: +Например, вот как вы определяете, что пропсу `color` по умолчанию должно быть `'blue'`: ```js {2-4} class Button extends Component { @@ -902,27 +914,27 @@ class Button extends Component { } ``` -If the `color` prop is not provided or is `undefined`, it will be set by default to `'blue'`: +Если пропс `color` не предоставлен или равен `undefined`, он будет установлен по умолчанию в `'blue'`: ```js <> - {/* this.props.color is "blue" */} + {/* this.props.color равен "blue" */}