From 9fe005caf3dd9c5c8af41ec55ea7b5018084962f Mon Sep 17 00:00:00 2001 From: Vitalii Burlai Date: Thu, 11 Apr 2019 15:12:55 +0100 Subject: [PATCH 1/5] Translation of Error Boundaries --- content/docs/error-boundaries.md | 102 +++++++++++++++---------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/content/docs/error-boundaries.md b/content/docs/error-boundaries.md index 147732911..bfd06e6d6 100644 --- a/content/docs/error-boundaries.md +++ b/content/docs/error-boundaries.md @@ -1,28 +1,28 @@ --- 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 не надавав можливості вчасно опрацювати їх в компонентах, і також не міг відновитися після них. -## Introducing Error Boundaries {#introducing-error-boundaries} +## Представляєм запобіжники (компоненти Error Boundary) {#introducing-error-boundaries} -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”. +Помилка JavaScript в деякій частині UI не повинна ламати весь застосунок. Для вирішення цієї проблеми React версії 16 вводить для користувачів новий концепт – «запобіжник» (error boundary). -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. +Запобіжники – це React-компоненти які **ловлять помилки JavaScript в усьому дереві своїх дочірніх компонентів, логують їх та відображають запасний UI** замість дерева компонентів, що зламалось. Запобіжники можуть ловити помилки в рендері, методах життєвого циклу та в конструкторах компонентів, що знаходяться в дереві під ними. -> 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,18 +32,18 @@ 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 + // Ви можете відрендерити будь-який власний запасний UI return

Something went wrong.

; } @@ -52,7 +52,7 @@ class ErrorBoundary extends React.Component { } ``` -Then you can use it as a regular component: +Потім використовуємо запобіжник як звичайний компонент: ```js @@ -60,53 +60,53 @@ Then you can use it as a regular component: ``` -Error boundaries work like a JavaScript `catch {}` block, but for components. Only class components can be error boundaries. In practice, most of the time you’ll want to declare an error boundary component once and use it throughout your application. +Запобіжники працюють як блок `catch {}` в JavaScript але для компонентів. Лише класові компоненти можуть бути запобіжниками. На практиці в більшості випадків буде доцільно оголосити один запобіжник і потім використовувати його по всьому додатку. -Note that **error boundaries only catch errors in the components below them in the tree**. An error boundary can’t catch an error within itself. If an error boundary fails trying to render the error message, the error will propagate to the closest error boundary above it. This, too, is similar to how catch {} block works in JavaScript. +Зверніть увагу, що **запобіжники можуть піймати помилки лише в компонентах, що знаходяться під ними в дереві компонентів**. Запобіжник не може піймати помилку в собі. Якщо він не зможе відрендерити повідомлення про помилку, то помилка поширеться до наступного запобіжника вище нього в дереві компонентів. Це також схоже на те, як працює блок `catch {}` в JavaScript. -## Live Demo {#live-demo} +## Жива демонстрація {#live-demo} -Check out [this example of declaring and using an error boundary](https://codepen.io/gaearon/pen/wqvxGa?editors=0010) with [React 16](/blog/2017/09/26/react-v16.0.html). +Подивіться [приклад оголошення і використання запобіжника](https://codepen.io/gaearon/pen/wqvxGa?editors=0010) в [React 16](/blog/2017/09/26/react-v16.0.html). -## Where to Place Error Boundaries {#where-to-place-error-boundaries} +## Де ставити запобіжники {#where-to-place-error-boundaries} -The granularity of error boundaries is up to you. You may wrap top-level route components to display a “Something went wrong” message to the user, just like server-side frameworks often handle crashes. You may also wrap individual widgets in an error boundary to protect them from crashing the rest of the application. +Вирішуйте на ваш розсуд як часто ставити запобіжники. Було б доцільно обгорнути компоненти маршрутів найвищого рівня щоб показати користувачеві повідомлення «Щось пішло не так», так само, як це часто робиться в фреймворках на стороні серверу. Ви також можете обгорнути в запобіжник окремі віджети щоб захистити решту додатку від збоїв в них. -## New Behavior for Uncaught Errors {#new-behavior-for-uncaught-errors} +## Нова поведінка не пійманих помилок {#new-behavior-for-uncaught-errors} -This change has an important implication. **As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree.** +Ця зміна має важливі наслідки. **Починаючи з React версії 16, помилки, які не були піймані жодним з запобіжників, призведуть до демонтування всього дерева React-компонентів.** -We debated this decision, but in our experience it is worse to leave corrupted UI in place than to completely remove it. For example, in a product like Messenger leaving the broken UI visible could lead to somebody sending a message to the wrong person. Similarly, it is worse for a payments app to display a wrong amount than to render nothing. +Ми довго обговорювали це рішення і, судячи з нашого досвіду, гірше було б залишити пошкоджений UI на місці ніж повністю його вилучити. Наприклад, в такому продукті як чат (Facebook Messenger), відображення пошкодженого UI може призвести до того, що хтось надіслав би повідомлення не тій людині. Аналогічно, ще гірше, у додатку з проведення платежів відобразити невірну суму, ніж не відобразити взагалі нічого. -This change means that as you migrate to React 16, you will likely uncover existing crashes in your application that have been unnoticed before. Adding error boundaries lets you provide better user experience when something goes wrong. +Ця зміна означає, що при переході на React версії 16 ви, найбільш ймовірно, виявите існуючі збої в вашому додатку, які були непомічені до цього. Додавання запобіжників дозволить вам надати кращий досвід користувачам якщо щось піде не так. -For example, Facebook Messenger wraps content of the sidebar, the info panel, the conversation log, and the message input into separate error boundaries. If some component in one of these UI areas crashes, the rest of them remain interactive. +Наприклад, Facebook Messenger огортає зміст бічної панелі, інформаційної панелі, історію повідомлень, та поле введення повідомлень в окремі запобіжники. Якщо якийсь компонент в одній з цих UI зон дасть збій, то решта зон залишаться працюючими. -We also encourage you to use JS error reporting services (or build your own) so that you can learn about unhandled exceptions as they happen in production, and fix them. +Ми також рекомендуємо вам використовувати існуючі служби звітування про помилки JS (або створити власну), таким чином ви зможете дізнатись про необроблені виняткові ситуації які відбулись в production та виправити їх. -## Component Stack Traces {#component-stack-traces} +## Стек викликів компонентів {#component-stack-traces} -React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them. In addition to the error message and the JavaScript stack, it also provides component stack traces. Now you can see where exactly in the component tree the failure has happened: +React 16 в режимі розробки друкує в консоль всі помилки, що відбулись під час рендеру, навіть якщо додаток ненавмисно їх поглинає. Додатково до повідомлення про помилку і стека викликів JavaScript, він також надає трасування стека компонентів. Тепер ви зможете побачити де саме в дереві компонентів відбувся збій: -Error caught by Error Boundary component +Помилка спіймана запобіжником -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): -Error caught by Error Boundary component with line numbers +Помилка з номерами рядків спіймана запобіжником -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, то ви можете додати вручну [цей плагін для трансформації коду](https://www.npmjs.com/package/babel-plugin-transform-react-jsx-source) до вашої конфігурації Babel. Зверніть увагу, що він призначений лише для режиму розробки і **повинен бути відключений в production**. -> 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/uk/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 +116,21 @@ try { } ``` -However, React components are declarative and specify *what* should be rendered: +Однак React-компоненти є декларативними, вказуючи *що* повинно бути відрендерено: ```js