diff --git a/content/docs/reference-react-component.md b/content/docs/reference-react-component.md
index ecb4d087c..cbe6b67d9 100644
--- a/content/docs/reference-react-component.md
+++ b/content/docs/reference-react-component.md
@@ -15,50 +15,50 @@ redirect_from:
- "tips/use-react-with-other-libraries.html"
---
-This page contains a detailed API reference for the React component class definition. It assumes you're familiar with fundamental React concepts, such as [Components and Props](/docs/components-and-props.html), as well as [State and Lifecycle](/docs/state-and-lifecycle.html). If you're not, read them first.
+Эта страница содержит подробный справочник API для определения классового компонента React. Предполагается, что вы знакомы с такими концепциями React, как [компоненты и пропсы](/docs/components-and-props.html), а также [состояние и жизненный цикл](/docs/state-and-lifecycle.html). Прочитайте про них, если вы этого не сделали.
-## Overview {#overview}
+## Обзор {#overview}
-React lets you define components as classes or functions. Components defined as classes currently provide more features which are described in detail on this page. To define a React component class, you need to extend `React.Component`:
+React позволяет определять компоненты как классы или функции. В настоящее время классовые компоненты имеют больше возможностей. Они разобраны на этой странице. Чтобы определить такой компонент, необходимо отнаследоваться от `React.Component`:
```js
class Welcome extends React.Component {
render() {
- return
Hello, {this.props.name}
;
+ return Привет, {this.props.name}
;
}
}
```
-The only method you *must* define in a `React.Component` subclass is called [`render()`](#render). All the other methods described on this page are optional.
+Единственный *обязательный* метод в подклассе `React.Component` – [`render()`](#render). Все остальные методы, описанные ниже, являются необязательными.
-**We strongly recommend against creating your own base component classes.** In React components, [code reuse is primarily achieved through composition rather than inheritance](/docs/composition-vs-inheritance.html).
+**Мы рекомендуем не создавать собственные классы базовых компонентов.** В компонентах React переиспользование кода обычно достигается за счет [композиции, а не наследования](/docs/composition-vs-inheritance.html).
->Note:
+> Примечание:
>
->React doesn't force you to use the ES6 class syntax. If you prefer to avoid it, you may use the `create-react-class` module or a similar custom abstraction instead. Take a look at [Using React without ES6](/docs/react-without-es6.html) to learn more.
+>React не заставляет вас использовать синтаксис классов из ES6. Вместо этого вы можете использовать модуль `create-react-class` или его аналоги. Посмотрите раздел [Использование React без ES6](/docs/react-without-es6.html), чтобы узнать больше.
-### The Component Lifecycle {#the-component-lifecycle}
+### Жизненный цикл компонента {#the-component-lifecycle}
-Each component has several "lifecycle methods" that you can override to run code at particular times in the process. **You can use [this lifecycle diagram](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) as a cheat sheet.** In the list below, commonly used lifecycle methods are marked as **bold**. The rest of them exist for relatively rare use cases.
+Каждый компонент имеет несколько «методов жизненного цикла». Переопределение такого метода позволяет выполнять код на конкретном этапе этого процесса. **Вы можете использовать [эту диаграмму жизненного цикла](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) как шпаргалку.** Далее на странице **полужирным шрифтом** выделены самые распространённые методы жизненного цикла.
-#### Mounting {#mounting}
+#### Монтирование {#mounting}
-These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
+При создании экземпляра компонента и его вставке в DOM, следующие методы вызываются в установленном порядке:
- [**`constructor()`**](#constructor)
- [`static getDerivedStateFromProps()`](#static-getderivedstatefromprops)
- [**`render()`**](#render)
- [**`componentDidMount()`**](#componentdidmount)
->Note:
+> Примечание:
>
->These methods are considered legacy and you should [avoid them](/blog/2018/03/27/update-on-async-rendering.html) in new code:
+> Этот метод устарел. [Не используйте его](/blog/2018/03/27/update-on-async-rendering.html) в новом коде.
>
>- [`UNSAFE_componentWillMount()`](#unsafe_componentwillmount)
-#### Updating {#updating}
+#### Обновление {#updating}
-An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
+Обновление происходит при изменении пропсов или состояния. Следующие методы вызываются в установленном порядке при повторном рендере компонента:
- [`static getDerivedStateFromProps()`](#static-getderivedstatefromprops)
- [`shouldComponentUpdate()`](#shouldcomponentupdate)
@@ -66,50 +66,50 @@ An update can be caused by changes to props or state. These methods are called i
- [`getSnapshotBeforeUpdate()`](#getsnapshotbeforeupdate)
- [**`componentDidUpdate()`**](#componentdidupdate)
->Note:
+> Примечание:
>
->These methods are considered legacy and you should [avoid them](/blog/2018/03/27/update-on-async-rendering.html) in new code:
+> Эти методы устарели. [Не используйте их](/blog/2018/03/27/update-on-async-rendering.html) в новом коде.
>
>- [`UNSAFE_componentWillUpdate()`](#unsafe_componentwillupdate)
>- [`UNSAFE_componentWillReceiveProps()`](#unsafe_componentwillreceiveprops)
-#### Unmounting {#unmounting}
+#### Размонтирование {#unmounting}
-This method is called when a component is being removed from the DOM:
+Этот метод вызывается при удалении компонента из DOM:
- [**`componentWillUnmount()`**](#componentwillunmount)
-#### Error Handling {#error-handling}
+#### Обработка ошибок {#error-handling}
-These methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.
+Следующие методы вызываются, если произошла ошибка в процессе рендеринга, методе жизненного цикла или конструкторе любого дочернего компонента.
- [`static getDerivedStateFromError()`](#static-getderivedstatefromerror)
- [`componentDidCatch()`](#componentdidcatch)
-### Other APIs {#other-apis}
+### Другие методы API {#other-apis}
-Each component also provides some other APIs:
+В каждом компоненте доступны методы API:
- [`setState()`](#setstate)
- [`forceUpdate()`](#forceupdate)
-### Class Properties {#class-properties}
+### Свойства класса {#class-properties}
- [`defaultProps`](#defaultprops)
- [`displayName`](#displayname)
-### Instance Properties {#instance-properties}
+### Свойства экземпляра {#instance-properties}
- [`props`](#props)
- [`state`](#state)
* * *
-## Reference {#reference}
+## Справочник {#reference}
-### Commonly Used Lifecycle Methods {#commonly-used-lifecycle-methods}
+### Распространённые методы жизненного цикла {#commonly-used-lifecycle-methods}
-The methods in this section cover the vast majority of use cases you'll encounter creating React components. **For a visual reference, check out [this lifecycle diagram](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/).**
+Методы в этом разделе охватывают большинство задач, с которыми вы столкнётесь при использовании React-компонентов. **Для визуального представления вы можете использовать [эту диаграмму жизненного цикла](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/).**
### `render()` {#render}
@@ -117,23 +117,23 @@ The methods in this section cover the vast majority of use cases you'll encounte
render()
```
-The `render()` method is the only required method in a class component.
+`render()` – единственный обязательный метод в классовом компоненте.
-When called, it should examine `this.props` and `this.state` and return one of the following types:
+При вызове он проверяет `this.props` и `this.state` и возвращает один из следующих вариантов:
-- **React elements.** Typically created via [JSX](/docs/introducing-jsx.html). For example, `` and `` are React elements that instruct React to render a DOM node, or another user-defined component, respectively.
-- **Arrays and fragments.** Let you return multiple elements from render. See the documentation on [fragments](/docs/fragments.html) for more details.
-- **Portals**. Let you render children into a different DOM subtree. See the documentation on [portals](/docs/portals.html) for more details.
-- **String and numbers.** These are rendered as text nodes in the DOM.
-- **Booleans or `null`**. Render nothing. (Mostly exists to support `return test && ` pattern, where `test` is boolean.)
+- **Элемент React.** Обычно создаётся с помощью [JSX](/docs/introducing-jsx.html). Указывает React, что рендерить: DOM-узел или пользовательский компонент. Например, `` или ``.
+- **Массивы и фрагменты.** Возвращает несколько элементов из `render()`. Подробнее про [фрагменты](/docs/fragments.html).
+- **Порталы**. Рендерит несколько дочерних элементов в другое поддерево DOM. Подробнее про [порталы](/docs/portals.html).
+- **Строки и числа.** Рендерит текстовые DOM-узлы.
+- **Booleans or `null`**. Ничего не рендерит. (Обычно необходим для поддержки паттерна `return test && `, где `test` – логическое значение.)
-The `render()` function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser.
+Функция `render()` должна быть *чистой*. Это означает, что она не изменяет состояние компонента, всегда возвращает один и тот же результат, не взаимодействует напрямую с браузером.
-If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes components easier to think about.
+Взаимодействовать с браузером необходимо в `componentDidMount()` или других методах жизненного цикла. *Чистый* `render()` делает компонент понятным.
-> Note
+> Примечание:
>
-> `render()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdate) returns false.
+> `render()` не вызывается, если [`shouldComponentUpdate()`](#shouldcomponentupdate) возвращает `false`.
* * *
@@ -143,48 +143,47 @@ If you need to interact with the browser, perform your work in `componentDidMoun
constructor(props)
```
-**If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.**
+**Вы можете не использовать конструктор в React-компоненте, если вы не определяете состояние или не привязываете методы.**
-The constructor for a React component is called before it is mounted. When implementing the constructor for a `React.Component` subclass, you should call `super(props)` before any other statement. Otherwise, `this.props` will be undefined in the constructor, which can lead to bugs.
+Конструктор компонента React вызывается до того, как компонент будет примонтирован. В начале конструктора необходимо вызывать `super(props)`. Если это не сделать, `this.props` не будет определен. Это может привести к багам.
-Typically, in React constructors are only used for two purposes:
+Конструкторы в React обычно используют для двух целей:
-* Initializing [local state](/docs/state-and-lifecycle.html) by assigning an object to `this.state`.
-* Binding [event handler](/docs/handling-events.html) methods to an instance.
+* Инициализация [внутреннего состояния](/docs/state-and-lifecycle.html) через присвоение объекта `this.state`.
+* Привязка [обработчиков событий](/docs/handling-events.html) к экземпляру.
-You **should not call `setState()`** in the `constructor()`. Instead, if your component needs to use local state, **assign the initial state to `this.state`** directly in the constructor:
+Вы **не должны вызывать `setState()`** в `constructor()`. Если вам нужно внутреннее состояние, **присвойте начальное состояние `this.state`** прямо в конструкторе.
```js
constructor(props) {
super(props);
- // Don't call this.setState() here!
+ // Не вызывайте здесь this.setState()!
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
```
-Constructor is the only place where you should assign `this.state` directly. In all other methods, you need to use `this.setState()` instead.
+Конструктор — единственное место, где можно напрямую изменять `this.state`. В остальных методах необходимо использовать `this.setState()`.
-Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use `componentDidMount()` instead.
+Не используйте побочные эффекты или подписки в конструкторе. Вместо этого используйте `componentDidMount()`.
->Note
+> Примечание:
>
->**Avoid copying props into state! This is a common mistake:**
+>**Не копируйте пропсы в состояние! Это распространённая ошибка:**
>
>```js
>constructor(props) {
> super(props);
-> // Don't do this!
+> // Не делайте этого!
> this.state = { color: props.color };
>}
>```
>
->The problem is that it's both unnecessary (you can use `this.props.color` directly instead), and creates bugs (updates to the `color` prop won't be reflected in the state).
+>Проблема в том, что это излишне и приводит к багам (обновления в пропе `color` не будут зафиксированы в состоянии). Вместо этого используйте `this.props.color`.
>
->**Only use this pattern if you intentionally want to ignore prop updates.** In that case, it makes sense to rename the prop to be called `initialColor` or `defaultColor`. You can then force a component to "reset" its internal state by [changing its `key`](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) when necessary.
+> **Используйте данный подход, если вы намеренно хотите игнорировать обновления пропсов.** В таком случае лучше переименовать проп в `initialColor` или `defaultColor`. После этого вы сможете заставить компонент «сбросить» своё внутреннее состояние, [изменив свой ключ](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key), когда это будет необходимо.
>
->Read our [blog post on avoiding derived state](/blog/2018/06/07/you-probably-dont-need-derived-state.html) to learn about what to do if you think you need some state to depend on the props.
-
+>Прочитайте нашу статью в блоге про [отсутствие необходимости в производном состоянии](/blog/2018/06/07/you-probably-dont-need-derived-state.html). Она описывает случаи, в которых вам необходимо состояние, зависящее от пропсов.
* * *
@@ -194,11 +193,11 @@ Avoid introducing any side-effects or subscriptions in the constructor. For thos
componentDidMount()
```
-`componentDidMount()` is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
+`componentDidMount()` вызывается сразу после монтирования (то есть, вставки компонента в DOM). В этом методе должны происходить действия, которые требуют наличия DOM-узлов. Это хорошее место для создания сетевых запросов.
-This method is a good place to set up any subscriptions. If you do that, don't forget to unsubscribe in `componentWillUnmount()`.
+Этот метод подходит для настройки подписок. Но не забудьте отписаться от них в `componentWillUnmount()`.
-You **may call `setState()` immediately** in `componentDidMount()`. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the `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()` 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()** в `componentDidMount()`. Это вызовет дополнительный рендер перед тем, как браузер обновит экран. Гарантируется, что пользователь не увидит промежуточное состояние, даже если `render()` будет вызываться дважды. Используйте этот подход с осторожностью, он может вызвать проблемы с производительностью. В большинстве случаев начальное состояние лучше объявить в `constructor()`. Однако, это может быть необходимо для случаев, когда нужно измерить размер или положение DOM-узла, на основе которого происходит рендер. Например, для модальных окон или всплывающих подсказок.
* * *
@@ -208,26 +207,27 @@ You **may call `setState()` immediately** in `componentDidMount()`. It will trig
componentDidUpdate(prevProps, prevState, snapshot)
```
-`componentDidUpdate()` is invoked immediately after updating occurs. This method is not called for the initial render.
+`componentDidUpdate()` вызывается сразу после обновления. Не вызывается при первом рендере.
-Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good 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).
+Метод позволяет работать с DOM при обновлении компонента. Также он подходит для выполнения таких сетевых запросов, которые выполняются на основании результата сравнения текущих пропсов с предыдущими. Если пропсы не изменились, новый запрос может и не требоваться.
```js
componentDidUpdate(prevProps) {
- // Typical usage (don't forget to compare props):
+ // Популярный пример (не забудьте сравнить пропсы):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
```
-You **may call `setState()` immediately** in `componentDidUpdate()` but note that **it must be wrapped in a condition** like in the example above, or you'll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance. If you're trying to "mirror" some state to a prop coming from above, consider using the prop directly instead. Read more about [why copying props into state causes bugs](/blog/2018/06/07/you-probably-dont-need-derived-state.html).
+Вы **можете сразу вызвать setState()** в `componentDidUpdate()`, если **оно находится в условии**, как в примере выше. Иначе может произойти бесконечный цикл.
+Это повлечёт за собой дополнительный, незаметный для пользователя, рендер, который повлияет на производительность компонента. Используйте пропсы для «отражения» некоторого состояния в пропсах, приходящих сверху. Подробнее о том, [почему копирование пропсов в состояние вызывает баги](/blog/2018/06/07/you-probably-dont-need-derived-state.html).
-If your component implements the `getSnapshotBeforeUpdate()` lifecycle (which is rare), the value it returns will be passed as a third "snapshot" parameter to `componentDidUpdate()`. Otherwise this parameter will be undefined.
+В тех редких случаях когда реализован метод жизненного цикла `getSnapshotBeforeUpdate()`, его результат передаётся `componentDidUpdate()` в качестве третьего параметра `snapshot`.
-> Note
+> Примечание:
>
-> `componentDidUpdate()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdate) returns false.
+> `componentDidUpdate()` не вызывается, если [`shouldComponentUpdate()`](#shouldcomponentupdate) возвращает `false`.
* * *
@@ -237,16 +237,15 @@ If your component implements the `getSnapshotBeforeUpdate()` lifecycle (which is
componentWillUnmount()
```
-`componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in `componentDidMount()`.
+`componentWillUnmount()` вызывается непосредственно перед размонтированием и удалением компонента. В этом методе выполняется необходимый сброс: отмена таймеров, сетевых запросов и подписок, созданных в `componentDidMount()`.
-You **should not call `setState()`** in `componentWillUnmount()` because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.
+**Не используйте setState()** в `componentWillUnmount()`, так как компонент никогда не рендерится повторно. После того, как экземпляр компонента будет размонтирован, он никогда не будет примонтирован снова.
* * *
-### Rarely Used Lifecycle Methods {#rarely-used-lifecycle-methods}
-
-The methods in this section correspond to uncommon use cases. They're handy once in a while, but most of your components probably don't need any of them. **You can see most of the methods below on [this lifecycle diagram](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) if you click the "Show less common lifecycles" checkbox at the top of it.**
+### Редко используемые методы жизненного цикла {#rarely-used-lifecycle-methods}
+Методы из этого раздела используются редко. В большинстве компонентов они не нужны, хотя иногда бывают полезны. **Вы можете увидеть большинство приведённых ниже методов на [этой диаграмме жизненного цикла](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/), если наверху страницы нажмете на чекбокс «Показать менее популярные методы жизненного цикла».**
### `shouldComponentUpdate()` {#shouldcomponentupdate}
@@ -254,17 +253,17 @@ The methods in this section correspond to uncommon use cases. They're handy once
shouldComponentUpdate(nextProps, nextState)
```
-Use `shouldComponentUpdate()` to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.
+Используйте `shouldComponentUpdate()`, чтобы указать необходимость следующего рендера на основе изменений состояния и пропсов. По умолчанию происходит повторный рендер при любом изменении состояния. В большинстве случаев вы должны полагаться на это поведение.
-`shouldComponentUpdate()` is invoked 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()` is used.
+`shouldComponentUpdate()` вызывается перед рендером, когда получает новые пропсы или состояние. Значение по умолчанию равно `true`. Этот метод не вызывается при первом рендере или когда используется `forceUpdate()`.
-This method only exists as a **[performance optimization](/docs/optimizing-performance.html).** Do not rely on it to "prevent" a rendering, as this can lead to bugs. **Consider using the built-in [`PureComponent`](/docs/react-api.html#reactpurecomponent)** instead of writing `shouldComponentUpdate()` by hand. `PureComponent` performs a shallow comparison of props and state, and reduces the chance that you'll skip a necessary update.
+Этот метод нужен только для **[повышения производительности](/docs/optimizing-performance.html).**. Но не опирайтесь на его возможность «предотвратить» рендер, это может привести к багам. Вместо этого **используйте [`PureComponent`](/docs/react-api.html#reactpurecomponent)**, который позволяет не описывать поведение `shouldComponentUpdate()` вручную. `PureComponent` поверхностно сравнивает пропсы и состояние и позволяет не пропустить необходимое обновление.
-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. Note that returning `false` does not prevent child components from re-rendering when *their* state changes.
+Если вы уверены, что хотите написать его вручную, вы можете сравнить `this.props` с `nextProps`, а `this.state` с `nextState`. Верните `false` чтобы пропустить обновление React. Возврат `false` не предотвращает повторный рендер дочерних компонентов при изменении *их* состояния.
-We do not recommend doing deep equality checks or using `JSON.stringify()` in `shouldComponentUpdate()`. It is very inefficient and will harm performance.
+Мы не рекомендуем делать глубокое сравнение или использовать `JSON.stringify()` в `shouldComponentUpdate()`. Это неэффективно и плохо влияет на производительность.
-Currently, if `shouldComponentUpdate()` returns `false`, then [`UNSAFE_componentWillUpdate()`](#unsafe_componentwillupdate), [`render()`](#render), and [`componentDidUpdate()`](#componentdidupdate) will not be invoked. In the future React may treat `shouldComponentUpdate()` as a hint rather than a strict directive, and returning `false` may still result in a re-rendering of the component.
+В настоящее время, если `shouldComponentUpdate()` возвращает `false`, то [`UNSAFE_componentWillUpdate()`](#unsafe_componentwillupdate), [`render()`](#render) и [`componentDidUpdate()`](#componentdidupdate) не будут вызваны. В будущем React может рассматривать `shouldComponentUpdate()` как подсказку, а не строгое указание. В таком случае возврат `false` сможет привести к повторному рендеру компонента.
* * *
@@ -274,22 +273,23 @@ Currently, if `shouldComponentUpdate()` returns `false`, then [`UNSAFE_component
static getDerivedStateFromProps(props, state)
```
-`getDerivedStateFromProps` is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
+`getDerivedStateFromProps` вызывается непосредственно перед вызовом метода `render`, как при начальном монтировании, так и при последующих обновлениях. Он должен вернуть объект для обновления состояния или null, чтобы ничего не обновлять.
+
+Этот метод существует для [редких случаев](/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state), когда состояние зависит от изменений в пропсах. Например, это подойдёт для реализации компонента ``, который сравнивает свои предыдущие и следующие дочерние компоненты, чтобы решить, какой из них нужно анимировать.
-This method exists for [rare use cases](/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state) where the state depends on changes in props over time. For example, it might be handy for implementing a `` component that compares its previous and next children to decide which of them to animate in and out.
+Производное состояние приводит к сложному коду и делает ваши компоненты сложными для понимания. Убедитесь, что вы знакомы с [простыми альтернативами:](/blog/2018/06/07/you-probably-dont-need-derived-state.html)
-Deriving state leads to verbose code and makes your components difficult to think about.
-[Make sure you're familiar with simpler alternatives:](/blog/2018/06/07/you-probably-dont-need-derived-state.html)
+* Чтобы **выполнить побочный эффект при изменении пропсов** (например, сетевой запрос или анимацию) используйте [`componentDidUpdate`](#componentdidupdate).
-* If you need to **perform a side effect** (for example, data fetching or an animation) in response to a change in props, use [`componentDidUpdate`](#componentdidupdate) lifecycle instead.
+* Чтобы **повторно вычислить данные при изменении пропсов**, используйте [функцию мемоизации](/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization).
-* If you want to **re-compute some data only when a prop changes**, [use a memoization helper instead](/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization).
+* Чтобы **«сбросить» некоторое состояние при изменении пропсов**, используйте [контролируемые компоненты](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) или [неконтролируемые компоненты с ключом](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key).
-* If you want to **"reset" some state when a prop changes**, consider either making a component [fully controlled](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) or [fully uncontrolled with a `key`](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) instead.
+Этот метод не имеет доступа к экземпляру компонента. Чтобы использовать пропсы, состояние и методы класса в `getDerivedStateFromProps()`, их нужно вынести за пределы класса в виде чистых функций.
-This method doesn't have access to the component instance. If you'd like, you can reuse some code between `getDerivedStateFromProps()` and the other class methods by extracting pure functions of the component props and state outside the class definition.
+Если вы хотите переиспользовать код между `getDerivedStateFromProps()` и другими методами класса, извлеките чистые функции пропсов и состояния компонента и поместите их вне определения класса.
-Note that this method is fired on *every* render, regardless of the cause. This is in contrast to `UNSAFE_componentWillReceiveProps`, which only fires when the parent causes a re-render and not as a result of a local `setState`.
+Обратите внимание, что этот метод запускается при каждом рендере, независимо от причины. Это отличается от метода `UNSAFE_componentWillReceiveProps`, который запускается только при повторном рендере родительского компонента, а не в результате вызова `setState`.
* * *
@@ -299,41 +299,40 @@ Note that this method is fired on *every* render, regardless of the cause. This
getSnapshotBeforeUpdate(prevProps, prevState)
```
-`getSnapshotBeforeUpdate()` is invoked right before the most recently rendered output is committed to e.g. 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 will be passed as a parameter to `componentDidUpdate()`.
+`getSnapshotBeforeUpdate()` вызывается прямо перед этапом «фиксирования» (например, перед добавлением в DOM). Он позволяет вашему компоненту брать некоторую информацию из DOM (например, положение прокрутки) перед её возможным изменением. Любое значение, возвращаемое этим методом жизненного цикла, будет передано как параметр `componentDidUpdate()`.
-This use case is not common, but it may occur in UIs like a chat thread that need to handle scroll position in a special way.
+Это применяется редко, но может быть полезно в таких интерфейсах, как цепочка сообщений в чатах, в которых позиция прокрутки обрабатывается особым образом.
-A snapshot value (or `null`) should be returned.
+Значение снимка (или `null`) должно быть возвращено.
-For example:
+Например:
`embed:react-component-reference/get-snapshot-before-update.js`
-In the above examples, it is important to read the `scrollHeight` property in `getSnapshotBeforeUpdate` because there may be delays between "render" phase lifecycles (like `render`) and "commit" phase lifecycles (like `getSnapshotBeforeUpdate` and `componentDidUpdate`).
+В примерах выше важно получить значение свойства `scrollHeight` в `getSnapshotBeforeUpdate` из-за того, что могут возникать задержки между этапами жизненного цикла «рендер» (например, `render`) и «фиксирование» (например, `getSnapshotBeforeUpdate` и `componentDidUpdate`).
* * *
-### Error boundaries {#error-boundaries}
+### Предохранители {#error-boundaries}
-[Error boundaries](/docs/error-boundaries.html) are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
+[Предохранители](/docs/error-boundaries.html) – это React-компоненты, которые перехватывают JavaScript-ошибки в любом месте их дочернего дерева компонентов. Затем логируют эти ошибки и отображают запасной интерфейс вместо "поломанного" дерева компонентов. Предохранители отлавливают ошибки при рендере, в методах жизненного цикла и в конструкторах всего дерева под ними.
-A class component becomes an error boundary if it defines either (or both) of the lifecycle methods `static getDerivedStateFromError()` or `componentDidCatch()`. Updating state from these lifecycles lets you capture an unhandled JavaScript error in the below tree and display a fallback UI.
+Классовый компонент становится предохранителем, если в нём используются методы жизненного цикла `static getDerivedStateFromError()` и (или) `componentDidCatch()`. Обновление состояния в этом методе жизненного цикла позволяет перехватить необработанную JavaScript-ошибку в дереве ниже и отобразить запасной интерфейс.
-Only use error boundaries for recovering from unexpected exceptions; **don't try to use them for control flow.**
+Используйте предохранители только для обработки неожиданных исключений, **не используйте их для управления потоком исполнения в вашем приложении.**
-For more details, see [*Error Handling in React 16*](/blog/2017/07/26/error-handling-in-react-16.html).
+Подробнее в разделе [*Предохранители в React 16*](/blog/2017/07/26/error-handling-in-react-16.html).
-> Note
->
-> Error boundaries only catch errors in the components **below** them in the tree. An error boundary can’t catch an error within itself.
+> Примечание:
+>
+> Предохранители перехватывают ошибки в компонентах **ниже** по дереву. Предохранители не могут поймать ошибку внутри себя.
### `static getDerivedStateFromError()` {#static-getderivedstatefromerror}
```javascript
static getDerivedStateFromError(error)
```
-This lifecycle is invoked after an error has been thrown by a descendant component.
-It receives the error that was thrown as a parameter and should return a value to update state.
+Этот метод жизненного цикла вызывается после возникновения ошибки у компонента-потомка. Он получает ошибку в качестве параметра и возвращает значение для обновления состояния.
```js{7-10,13-16}
class ErrorBoundary extends React.Component {
@@ -343,25 +342,24 @@ class ErrorBoundary extends React.Component {
}
static getDerivedStateFromError(error) {
- // Update state so the next render will show the fallback UI.
+ // Обновите состояние так, чтобы следующий рендер показал запасной интерфейс.
return { hasError: true };
}
render() {
if (this.state.hasError) {
- // You can render any custom fallback UI
+ // Здесь можно рендерить запасной интерфейс
return Something went wrong.
;
}
- return this.props.children;
+ return this.props.children;
}
}
```
-> Note
+> Примечание:
>
-> `getDerivedStateFromError()` is called during the "render" phase, so side-effects are not permitted.
-For those use cases, use `componentDidCatch()` instead.
+> `getDerivedStateFromError()` вызывается во время этапа "рендера". Поэтому здесь запрещены любые побочные эффекты, но их можно использовать в `componentDidCatch()`.
* * *
@@ -371,15 +369,12 @@ For those use cases, use `componentDidCatch()` instead.
componentDidCatch(error, info)
```
-This lifecycle is invoked after an error has been thrown by a descendant component.
-It receives two parameters:
-
-1. `error` - The error that was thrown.
-2. `info` - An object with a `componentStack` key containing [information about which component threw the error](/docs/error-boundaries.html#component-stack-traces).
+Этот метод жизненного цикла вызывается после возникновения ошибки у компонента-потомка. Он получает два параметра:
+1. `error` - перехваченная ошибка
+2. `info` - объект с ключом `componentStack`, содержащий [информацию о компоненте, в котором произошла ошибка](/docs/error-boundaries.html#component-stack-traces).
-`componentDidCatch()` is called during the "commit" phase, so side-effects are permitted.
-It should be used for things like logging errors:
+`componentDidCatch()` вызывается во время этапа "фиксации", поэтому здесь можно использовать побочные эффекты. Метод можно использовать для логирования ошибок.
```js{12-19}
class ErrorBoundary extends React.Component {
@@ -389,12 +384,12 @@ class ErrorBoundary extends React.Component {
}
static getDerivedStateFromError(error) {
- // Update state so the next render will show the fallback UI.
+ // Обновите состояние так, чтобы следующий рендер показал запасной интерфейс.
return { hasError: true };
}
componentDidCatch(error, info) {
- // Example "componentStack":
+ // Пример "componentStack":
// in ComponentThatThrows (created by App)
// in ErrorBoundary (created by App)
// in div (created by App)
@@ -404,25 +399,25 @@ class ErrorBoundary extends React.Component {
render() {
if (this.state.hasError) {
- // You can render any custom fallback UI
+ // Здесь можно рендерить запасной интерфейс
return Something went wrong.
;
}
- return this.props.children;
+ return this.props.children;
}
}
```
-> Note
->
-> In the event of an error, you can render a fallback UI with `componentDidCatch()` by calling `setState`, but this will be deprecated in a future release.
-> Use `static getDerivedStateFromError()` to handle fallback rendering instead.
+> Примечание:
+>
+>В случае ошибки вы можете рендерить запасной интерфейс с помощью `componentDidCatch()`, вызвав `setState`. Однако, этот способ скоро будет считаться устаревшим.
+> Используйте `static getDerivedStateFromError()` для рендера резервного интерфейса.
* * *
-### Legacy Lifecycle Methods {#legacy-lifecycle-methods}
+### Устаревшие методы жизненного цикла {#legacy-lifecycle-methods}
-The lifecycle methods below are marked as "legacy". They still work, but we don't recommend using them in the new code. You can learn more about migrating away from legacy lifecycle methods in [this blog post](/blog/2018/03/27/update-on-async-rendering.html).
+Приведённые ниже методы жизненного цикла устарели. Их не рекомендуется использовать в новом коде, хотя они продолжают работать. Вы можете узнать больше о переходе с устаревших методов жизненного цикла в [блоге](/blog/2018/03/27/update-on-async-rendering.html).
### `UNSAFE_componentWillMount()` {#unsafe_componentwillmount}
@@ -430,15 +425,15 @@ The lifecycle methods below are marked as "legacy". They still work, but we don'
UNSAFE_componentWillMount()
```
-> Note
+> Примечание:
>
-> This lifecycle was previously named `componentWillMount`. That name will continue to work until version 17. Use the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components.
+> Этот метод жизненного цикла раньше назывался `componentWillMount`. По этому названию он будет доступен до 17 версии. Чтобы автоматически обновить компоненты, используйте [`rename-unsafe-lifecycles`](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles).
-`UNSAFE_componentWillMount()` is invoked just before mounting occurs. It is called before `render()`, therefore calling `setState()` synchronously in this method will not trigger an extra rendering. Generally, we recommend using the `constructor()` instead for initializing state.
+`UNSAFE_componentWillMount()` вызывается непосредственно перед монтированием. Он вызывается перед `render()`, поэтому синхронный вызов `setState()` в этом методе не вызовет дополнительный рендер. Для инициализации состояния мы рекомендуем использовать `constructor()`.
-Avoid introducing any side-effects or subscriptions in this method. For those use cases, use `componentDidMount()` instead.
+Избегайте добавления каких-либо побочных эффектов или подписок в этом методе. Вместо этого используйте `componentDidMount()`.
-This is the only lifecycle method called on server rendering.
+Это единственный метод жизненного цикла, вызываемый при серверном рендеринге.
* * *
@@ -448,25 +443,25 @@ This is the only lifecycle method called on server rendering.
UNSAFE_componentWillReceiveProps(nextProps)
```
-> Note
+> Примечание:
>
-> This lifecycle was previously named `componentWillReceiveProps`. That name will continue to work until version 17. Use the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components.
+> Этот метод жизненного цикла раньше назывался `componentWillReceiveProps`. По этому названию он будет доступен до 17 версии. Чтобы автоматически обновить компоненты, используйте [`rename-unsafe-lifecycles`](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles).
-> Note:
+> Примечание:
>
-> Using this lifecycle method often leads to bugs and inconsistencies
+> Использование этого метода жизненного цикла часто приводило к багам
>
-> * If you need to **perform a side effect** (for example, data fetching or an animation) in response to a change in props, use [`componentDidUpdate`](#componentdidupdate) lifecycle instead.
-> * If you used `componentWillReceiveProps` for **re-computing some data only when a prop changes**, [use a memoization helper instead](/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization).
-> * If you used `componentWillReceiveProps` to **"reset" some state when a prop changes**, consider either making a component [fully controlled](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) or [fully uncontrolled with a `key`](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) instead.
+> * Чтобы **выполнить побочный эффект при изменении пропсов** (например, сетевой запрос или анимацию) используйте [`componentDidUpdate`](#componentdidupdate).
+> * Чтобы **повторно вычислить данные при изменении пропсов** вместо `componentWillReceiveProps` используйте [функцию мемоизации](/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization).
+> * Чтобы **«сбросить» некоторое состояние при изменении пропсов** вместо `componentWillReceiveProps` используйте [контролируемые компоненты](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) или [неконтролируемые компоненты с ключом](/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key).
>
-> For other use cases, [follow the recommendations in this blog post about derived state](/blog/2018/06/07/you-probably-dont-need-derived-state.html).
+> Другие рекомендации можно посмотреть [в статье про производное состояние](/blog/2018/06/07/you-probably-dont-need-derived-state.html).
-`UNSAFE_componentWillReceiveProps()` is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare `this.props` and `nextProps` and perform state transitions using `this.setState()` in this method.
+`UNSAFE_componentWillReceiveProps()` вызывается до того, как смонтированный компонент получит новые пропсы. Чтобы обновить состояние в ответ на изменение пропсов (например, для его сброса), можно сравнить `this.props` с `nextProps` и обновить состояние в этом методе с помощью `this.setState()`.
-Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. Make sure to compare the current and next values if you only want to handle changes.
+Обратите внимание, если родительский компонент заставляет ваш компонент повторно рендериться, метод будет вызываться, даже если пропсы не изменились. Убедитесь, что сравниваете текущие и следующие значения, если вы хотите обрабатывать изменения.
-React doesn't call `UNSAFE_componentWillReceiveProps()` with initial props during [mounting](#mounting). It only calls this method if some of component's props may update. Calling `this.setState()` generally doesn't trigger `UNSAFE_componentWillReceiveProps()`.
+Во время [монтирования](#mounting) React не вызывает `UNSAFE_componentWillReceiveProps()` с начальными значениями пропсов. Этот метод вызывается, если некоторые пропсы компонента могут обновиться. Вызов `this.setState()` обычно не вызывает `UNSAFE_componentWillReceiveProps()`.
* * *
@@ -476,27 +471,27 @@ React doesn't call `UNSAFE_componentWillReceiveProps()` with initial props durin
UNSAFE_componentWillUpdate(nextProps, nextState)
```
-> Note
+> Примечание:
>
-> This lifecycle was previously named `componentWillUpdate`. That name will continue to work until version 17. Use the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components.
+> Этот метод жизненного цикла раньше назывался `componentWillUpdate`. По этому названию он будет доступен до 17 версии. Чтобы автоматически обновить компоненты, используйте [`rename-unsafe-lifecycles`](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles).
-`UNSAFE_componentWillUpdate()` is invoked just before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.
+`UNSAFE_componentWillUpdate()` вызывается непосредственно перед рендером при получении новых пропсов или состояния. В этом методе можно выполнить некоторую подготовку перед обновлением. Этот метод не вызывается при первом рендере.
-Note that you cannot call `this.setState()` here; nor should you do anything else (e.g. dispatch a Redux action) that would trigger an update to a React component before `UNSAFE_componentWillUpdate()` returns.
+Внутри этого метода нельзя вызвать `this.setState()`, а также делать какие-либо действия, которые влияют на обновление компонента перед возвратом `UNSAFE_componentWillUpdate()` (например, отправка действия Redux).
-Typically, this method can be replaced by `componentDidUpdate()`. If you were reading from the DOM in this method (e.g. to save a scroll position), you can move that logic to `getSnapshotBeforeUpdate()`.
+Обычно этот метод можно заменить на `componentDidUpdate()`. Вы можете использовать `getSnapshotBeforeUpdate()` для работы с DOM (например, запоминать положение прокрутки страницы).
-> Note
+> Примечание:
>
-> `UNSAFE_componentWillUpdate()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdate) returns false.
+> `UNSAFE_componentWillUpdate()` не вызывается, если [`shouldComponentUpdate()`](#shouldcomponentupdate) возвращает `false`.
* * *
-## Other APIs {#other-apis-1}
+## Другие APIs {#other-apis-1}
-Unlike the lifecycle methods above (which React calls for you), the methods below are the methods *you* can call from your components.
+В отличие от методов жизненного цикла, представленных выше (React вызывает их сам), методы, приведённые ниже, можно вызывать из компонентов.
-There are just two of them: `setState()` and `forceUpdate()`.
+Их всего два: `setState()` и `forceUpdate()`.
### `setState()` {#setstate}
@@ -504,21 +499,21 @@ There are just two of them: `setState()` and `forceUpdate()`.
setState(updater[, callback])
```
-`setState()` enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
+`setState()` добавляет в очередь изменения в состоянии компонента. Также он указывает React, что компонент и его дочерние элементы должны быть повторно отрендерены с обновлённым состоянием. Этот метод используется для обновления интерфейса в ответ на обработчики событий и ответы сервера.
-Think of `setState()` as a *request* rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
+Думайте о `setState()`, как о *запросе*, а не как о команде немедленного обновления компонента. Для увеличения производительности React может задержать его выполнение, а затем обновить несколько компонентов за один проход. React не гарантирует моментальное применение изменений в состоянии.
-`setState()` does not always immediately update the component. It may batch or defer the update until later. This makes reading `this.state` right after calling `setState()` a potential pitfall. Instead, use `componentDidUpdate` or a `setState` callback (`setState(updater, callback)`), 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, read about the `updater` argument below.
+Метод `setState()` не всегда обновляет компонент сразу. Он может группировать или откладывать обновление до следующего раза. Это делает чтение `this.state` сразу после вызова `setState()` потенциальной ловушкой. Вместо этого используйте `componentDidUpdate()` или колбэк `setState()` (`setState(updater, callback)`), каждый из которых гарантированно вызывается после того как было применено обновление. Если вам нужно обновить состояние на основе предыдущего, используйте аргумент `updater`, описанный ниже.
-`setState()` will always lead to a re-render unless `shouldComponentUpdate()` returns `false`. If mutable objects are being used and conditional rendering logic cannot be implemented in `shouldComponentUpdate()`, calling `setState()` only when the new state differs from the previous state will avoid unnecessary re-renders.
+`setState()` всегда приводит к повторному рендеру, если только `shouldComponentUpdate()` не возвращает `false`. Если используются мутабельные объекты, и условие рендеринга не может быть реализовано в `shouldComponentUpdate()`, вызывайте `setState()` только при разнице следующего и предыдущего состояния. Это предотвратит ненужные повторные рендеры.
-The first argument is an `updater` function with the signature:
+Первым аргументом передаётся функция `updater`, которая имеет следующий вид:
```javascript
(state, props) => stateChange
```
-`state` is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from `state` and `props`. For instance, suppose we wanted to increment a value in state by `props.step`:
+`state` – ссылка на состояние компонента при изменении. Объект состояния не должен мутировать. Изменения должны проявляться в виде нового объекта на основе входных данных из `state` и` props`. Предположим, что мы хотели бы увеличить значение состояния с помощью `props.step`:
```javascript
this.setState((state, props) => {
@@ -526,23 +521,23 @@ this.setState((state, props) => {
});
```
-Both `state` and `props` received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with `state`.
+Как `state`, так и` props`, полученные функцией обновления, гарантированно будут обновлены. Результат функции поверхностно объединяется с `state`.
-The second parameter to `setState()` is an optional callback function that will be executed once `setState` is completed and the component is re-rendered. Generally we recommend using `componentDidUpdate()` for such logic instead.
+Второй параметр в `setState()` - дополнительный колбэк, который выполняется после того, как исполнится `setState` и произойдёт повторный рендер компонента. Мы рекомендуем использовать такой подход в `componentDidUpdate()`.
-You may optionally pass an object as the first argument to `setState()` instead of a function:
+В качестве первого аргумента `setState()`, вместо функции, вы можете передать объект:
```javascript
setState(stateChange[, callback])
```
-This performs a shallow merge of `stateChange` into the new state, e.g., to adjust a shopping cart item quantity:
+В нём образуется новое состояние после поверхностного объединения с `stateChange`. Например, установим количество товаров в корзине:
```javascript
this.setState({quantity: 2})
```
-This form of `setState()` is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:
+Эта форма записи `setState()` также асинхронна, и несколько вызовов в течение одного цикла могут быть объединены вместе. Например, вам нужно увеличить количество элементов несколько раз в одном цикле. Результат этого можно представить так:
```javaScript
Object.assign(
@@ -553,7 +548,7 @@ Object.assign(
)
```
-Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:
+Последующие вызовы будут переопределять значения из предыдущих вызовов того же цикла. Из-за этого количество увеличится только один раз. В случае, если следующее состояние зависит от текущего, мы рекомендуем использовать форму функции обновления:
```js
this.setState((state) => {
@@ -561,11 +556,11 @@ this.setState((state) => {
});
```
-For more detail, see:
+Для более подробной информации смотрите:
-* [State and Lifecycle guide](/docs/state-and-lifecycle.html)
-* [In depth: When and why are `setState()` calls batched?](https://stackoverflow.com/a/48610973/458193)
-* [In depth: Why isn't `this.state` updated immediately?](https://github.com/facebook/react/issues/11527#issuecomment-360199710)
+* [Руководство по состоянию и жизненному циклу](/docs/state-and-lifecycle.html)
+* [Продвинутый уровень: когда и почему группируются вызовы `setState()`?](https://stackoverflow.com/a/48610973/458193)
+* [Продвинутый уровень: почему `this.state` не обновляется сразу?](https://github.com/facebook/react/issues/11527#issuecomment-360199710)
* * *
@@ -575,19 +570,19 @@ For more detail, see:
component.forceUpdate(callback)
```
-By default, when your component's state or props change, your component will re-render. If your `render()` method depends on some other data, you can tell React that the component needs re-rendering by calling `forceUpdate()`.
+По умолчанию при изменении состояния компонента или пропсов, происходит повторный рендер. Если ваш метод `render()` зависит от некоторых других данных, вы можете указать React необходимость в повторном рендере, вызвав `forceUpdate()`.
-Calling `forceUpdate()` will cause `render()` to be called on the component, skipping `shouldComponentUpdate()`. This will trigger the normal lifecycle methods for child components, including the `shouldComponentUpdate()` method of each child. React will still only update the DOM if the markup changes.
+Вызов `forceUpdate()` приведёт к выполнению метода `render()` в компоненте, пропуская `shouldComponentUpdate()`. Это вызовет обычные методы жизненного цикла для дочерних компонентов, включая `shouldComponentUpdate()` каждого дочернего компонента. React по-прежнему будет обновлять DOM только в случае изменения разметки.
-Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`.
+Чаще всего, `forceUpdate()` не используется. Вместо этого используются в `render()` данные из `this.props` и `this.state`.
* * *
-## Class Properties {#class-properties-1}
+## Свойства класса {#class-properties-1}
### `defaultProps` {#defaultprops}
-`defaultProps` can be defined as a property on the component class itself, to set the default props for the class. This is used for undefined props, but not for null props. For example:
+`defaultProps` можно определить как свойство самого класса компонента, которое позволяет установить пропсы класса по умолчанию. Это используется для неопределённых (`undefined`) пропсов, но не для пропсов со значением `null`. Например:
```js
class CustomButton extends React.Component {
@@ -595,11 +590,11 @@ class CustomButton extends React.Component {
}
CustomButton.defaultProps = {
- color: 'blue'
+ color: 'синий'
};
```
-If `props.color` is not provided, it will be set by default to `'blue'`:
+Если `props.color` не передаётся, по умолчанию установится `'синий'`:
```js
render() {
@@ -607,7 +602,7 @@ If `props.color` is not provided, it will be set by default to `'blue'`:
}
```
-If `props.color` is set to null, it will remain null:
+Если `props.color` имеет значение `null`, оно останется `null`:
```js
render() {
@@ -619,24 +614,24 @@ If `props.color` is set to null, it will remain null:
### `displayName` {#displayname}
-The `displayName` string is used in debugging messages. Usually, you don't need to set it explicitly because it's inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component, see [Wrap the Display Name for Easy Debugging](/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging) for details.
+Строка `displayName` используется в сообщениях для отладки. Обычно вам не нужно её явно указывать. По умолчанию используется имя функции или класса, указанное при определении компонента. Если вам нужно установить его явно, например, для отладки или создания компонента высшего порядка, посмотрите раздел [Обертка отображаемого имени для простой отладки](/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging).
* * *
-## Instance Properties {#instance-properties-1}
+## Свойства экземпляра {#instance-properties-1}
### `props` {#props}
-`this.props` contains the props that were defined by the caller of this component. See [Components and Props](/docs/components-and-props.html) for an introduction to props.
+`this.props` содержит свойства, которые были определены тем, кто вызывает этот компонент. Подробнее об этом можно узнать в разделе [Компоненты и пропсы](/docs/components-and-props.html)
-In particular, `this.props.children` is a special prop, typically defined by the child tags in the JSX expression rather than in the tag itself.
+Существует специальный проп `this.props.children`, который обычно определяется дочерними тегами в JSX-выражении, а не в самом теге.
### `state` {#state}
-The state contains data specific to this component that may change over time. The state is user-defined, and it should be a plain JavaScript object.
+Состояние содержит данные, специфичные для этого компонента. Они могут измениться со временем. Состояние определяется пользователем и должно быть простым объектом JavaScript.
-If some value isn't used for rendering or data flow (for example, a timer ID), you don't have to put it in the state. Such values can be defined as fields on the component instance.
+Вам не нужно вставлять в состояние значение, если оно не используется для рендера или потока данных (например, идентификатор таймера). Такие значения можно определить как поля экземпляра компонента.
-See [State and Lifecycle](/docs/state-and-lifecycle.html) for more information about the state.
+Дополнительную информацию можно найти в разделе [Состояние и жизненный цикл](/docs/state-and-lifecycle.html).
-Never mutate `this.state` directly, as calling `setState()` afterwards may replace the mutation you made. Treat `this.state` as if it were immutable.
+Никогда не мутируйте `this.state` напрямую, так как более поздний вызов `setState()` может перезаписать эту мутацию. Относитесь к `this.state` как к иммутабельному объекту.
diff --git a/examples/react-component-reference/get-snapshot-before-update.js b/examples/react-component-reference/get-snapshot-before-update.js
index cf1fb2335..6dbdf5e02 100644
--- a/examples/react-component-reference/get-snapshot-before-update.js
+++ b/examples/react-component-reference/get-snapshot-before-update.js
@@ -5,8 +5,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;
@@ -15,9 +15,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;