diff --git a/content/docs/error-boundaries.md b/content/docs/error-boundaries.md index 147732911..c59979a67 100644 --- a/content/docs/error-boundaries.md +++ b/content/docs/error-boundaries.md @@ -1,28 +1,27 @@ --- id: error-boundaries -title: Error Boundaries +title: Предохранители permalink: docs/error-boundaries.html --- -In the past, JavaScript errors inside components used to corrupt React’s internal state and cause it to [emit](https://github.com/facebook/react/issues/4026) [cryptic](https://github.com/facebook/react/issues/6895) [errors](https://github.com/facebook/react/issues/8579) on next renders. These errors were always caused by an earlier error in the application code, but React did not provide a way to handle them gracefully in components, and could not recover from them. +Ранее ошибки JavaScript внутри компонентов портили внутреннее состояние React и заставляли его [выдавать](https://github.com/facebook/react/issues/4026) [таинственные](https://github.com/facebook/react/issues/6895) [сообщения об ошибках](https://github.com/facebook/react/issues/8579) во время следующего рендера. Эти сообщения всегда вызывались ошибками, расположенными где-то выше в коде приложения, но React не предоставлял способа адекватно обрабатывать их в компонентах и не мог обработать их самостоятельно. +## Представляем предохранители (компоненты Error Boundary) {#introducing-error-boundaries} -## Introducing Error Boundaries {#introducing-error-boundaries} +Ошибка JavaScript где-то в коде UI не должна прерывать работу всего приложения. Чтобы исправить эту проблему для React-пользователей, React 16 ввводит концепцию "предохранителя" (error boundary). -A JavaScript error in a part of the UI shouldn’t break the whole app. To solve this problem for React users, React 16 introduces a new concept of an “error boundary”. +Предохранители это компоненты React, которые **отлавливают ошибки JavaScript в любом месте деревьев их дочерних компонентов, сохраняют их в журнале ошибок и выводят запасной UI** вместо рухнувшего дерева компонентов. Предохранители отлавливают ошибки при рендеринге, в методах жизненного цикла и конструкторах деревьев компонентов, расположенных под ними. -Error boundaries 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. - -> Note +> Примечание > -> Error boundaries do **not** catch errors for: +> Предохранители **не** поймают ошибки в: > -> * Event handlers ([learn more](#how-about-event-handlers)) -> * Asynchronous code (e.g. `setTimeout` or `requestAnimationFrame` callbacks) -> * Server side rendering -> * Errors thrown in the error boundary itself (rather than its children) +> * обработчиках событий ([подробнее](#how-about-event-handlers)); +> * асинхронном коде (например колбэках из `setTimeout` или `requestAnimationFrame`); +> * серверном рендеринге (Server-side rendering); +> * самом предохранителе (а не в его дочерних компонентах). -A class component becomes an error boundary if it defines either (or both) of the lifecycle methods [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) or [`componentDidCatch()`](/docs/react-component.html#componentdidcatch). Use `static getDerivedStateFromError()` to render a fallback UI after an error has been thrown. Use `componentDidCatch()` to log error information. +Классовый компонент является предохранителем, если он включает хотя бы один из следующих методов жизненного цикла: [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) или [`componentDidCatch()`](/docs/react-component.html#componentdidcatch). Используйте `static getDerivedStateFromError()` при рендеринге запасного UI в случае отлова ошибки. Используйте `componentDidCatch()` при написании кода для журналирования информации об отловленной ошибке. ```js{7-10,12-15,18-21} class ErrorBoundary extends React.Component { @@ -32,19 +31,19 @@ class ErrorBoundary extends React.Component { } static getDerivedStateFromError(error) { - // Update state so the next render will show the fallback UI. + // Обновить состояние с тем, чтобы следующий рендер показал запасной UI. return { hasError: true }; } componentDidCatch(error, info) { - // You can also log the error to an error reporting service + // Можно также сохранить информацию об ошибке в соответствующую службу журнала ошибок logErrorToMyService(error, info); } render() { if (this.state.hasError) { - // You can render any custom fallback UI - return
+
-You can also see the filenames and line numbers in the component stack trace. This works by default in [Create React App](https://github.com/facebookincubator/create-react-app) projects:
+Кроме этого, в стеке вызовов компонентов выводятся имена файлов и номера строк. Такое поведение по умолчанию настроено в проектах, созданных при помощи [Create React App](https://github.com/facebookincubator/create-react-app):
-
+
-If you don’t use Create React App, you can add [this plugin](https://www.npmjs.com/package/babel-plugin-transform-react-jsx-source) manually to your Babel configuration. Note that it’s intended only for development and **must be disabled in production**.
+Если вы не пользуетесь Create React App, вы можете вручную добавить к вашей конфигурации Babel [вот этот плагин](https://www.npmjs.com/package/babel-plugin-transform-react-jsx-source). Обратите внимание, что он предназначен исключительно для режима разработки и **должен быть отключён в продакшен**.
-> Note
+> Примечание
>
-> Component names displayed in the stack traces depend on the [`Function.name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name) property. If you support older browsers and devices which may not yet provide this natively (e.g. IE 11), consider including a `Function.name` polyfill in your bundled application, such as [`function.name-polyfill`](https://github.com/JamesMGreene/Function.name). Alternatively, you may explicitly set the [`displayName`](/docs/react-component.html#displayname) property on all your components.
-
+> Имена компонентов, выводимые в их стеке вызовов, определяются свойством [`Function.name`](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/name). Если ваше приложение поддерживает более старые браузеры и устройства, которые могут ещё не предоставлять его нативно (например, IE 11), рассмотрите возможность включения полифилла `Function.name` в бандл вашего приложения, например [`function.name-polyfill`](https://github.com/JamesMGreene/Function.name). В качестве альтернативы, вы можете явным образом задать проп [`displayName`](/docs/react-component.html#displayname) в каждом из ваших компонентов.
-## How About try/catch? {#how-about-trycatch}
+## А как насчёт try/catch? {#how-about-trycatch}
-`try` / `catch` is great but it only works for imperative code:
+`try` / `catch` — отличная конструкция, но она работает исключительно в императивном коде:
```js
try {
@@ -116,21 +114,21 @@ try {
}
```
-However, React components are declarative and specify *what* should be rendered:
+В то время, как компоненты React являются декларативными, указывая *что* должно быть отрендерено:
```js
```
-Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a `componentDidUpdate` method caused by a `setState` somewhere deep in the tree, it will still correctly propagate to the closest error boundary.
+Предохранители сохраняют декларативную природу React и ведут себя так, как вы уже привыкли ожидать от компонентов React. Например, если ошибка, произошедшая в методе `componentDidUpdate`, будет вызвана `setState` где-то в глубине дерева компонентов, она всё равно корректно всплывёт к ближайшему предохранителю.
-## How About Event Handlers? {#how-about-event-handlers}
+## А что насчёт обработчиков событий? {#how-about-event-handlers}
-Error boundaries **do not** catch errors inside event handlers.
+Предохранители **не** отлавливают ошибки, произошедшие в обработчиках событий.
-React doesn't need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle methods, the event handlers don't happen during rendering. So if they throw, React still knows what to display on the screen.
+React не нуждается в предохранителях, чтобы корректно обработать ошибки в обработчиках событий. В отличие от метода `render` и методов жизненного цикла, обработчики событий не выполняются во время рендеринга. Таким образом, даже если они сгенерируют ошибку, React всё равно знает, что нужно выводить на экран.
-If you need to catch an error inside event handler, use the regular JavaScript `try` / `catch` statement:
+Чтобы отловить ошибку в обработчике событий, пользуйтесь обычной JavaScript-конструкцией `try` / `catch`:
```js{9-13,17-20}
class MyComponent extends React.Component {
@@ -142,7 +140,7 @@ class MyComponent extends React.Component {
handleClick() {
try {
- // Do something that could throw
+ // Делаем что-то, что сгенерирует ошибку
} catch (error) {
this.setState({ error });
}
@@ -150,17 +148,17 @@ class MyComponent extends React.Component {
render() {
if (this.state.error) {
- return