diff --git a/content/blog/2018-10-23-react-v-16-6.md b/content/blog/2018-10-23-react-v-16-6.md index 4491d773a..42ee1790a 100644 --- a/content/blog/2018-10-23-react-v-16-6.md +++ b/content/blog/2018-10-23-react-v-16-6.md @@ -1,25 +1,25 @@ --- -title: "React v16.6.0: lazy, memo and contextType" +title: "React v16.6.0: lazy, memo и contextType" author: [sebmarkbage] --- -Today we're releasing React 16.6 with a few new convenient features. A form of PureComponent/shouldComponentUpdate for function components, a way to do code splitting using Suspense and an easier way to consume Context from class components. +Сегодня мы выпускаем React 16.6 с несколькими новыми удобными возможностями: версию PureComponent/shouldComponentUpdate для функциональных компонентов, способ разделения кода при помощи Suspense и упрощённый доступ к контексту из классовых компонентов. -Check out the full [changelog](#changelog) below. +Полный список изменений [описан далее в посте](#changelog). ## [`React.memo`](/docs/react-api.html#reactmemo) {#reactmemo} -Class components can bail out from rendering when their input props are the same using [`PureComponent`](/docs/react-api.html#reactpurecomponent) or [`shouldComponentUpdate`](/docs/react-component.html#shouldcomponentupdate). Now you can do the same with function components by wrapping them in [`React.memo`](/docs/react-api.html#reactmemo). +Классовые компоненты при помощи [`PureComponent`](/docs/react-api.html#reactpurecomponent) или [`shouldComponentUpdate`](/docs/react-component.html#shouldcomponentupdate) могут останавливать рендеринг, если пропсы не изменились. Теперь это доступно и в функциональных компонентах, если обернуть их в [`React.memo`](/docs/react-api.html#reactmemo). ```js const MyComponent = React.memo(function MyComponent(props) { - /* only rerenders if props change */ + /* повторный рендер пройдёт только при изменении пропсов */ }); ``` -## [`React.lazy`](/docs/code-splitting.html#reactlazy): Code-Splitting with `Suspense` {#reactlazy-code-splitting-with-suspense} +## [`React.lazy`](/docs/code-splitting.html#reactlazy): разделение кода при помощи `Suspense` {#reactlazy-code-splitting-with-suspense} -You may have seen [Dan's talk about React Suspense at JSConf Iceland](/blog/2018/03/01/sneak-peek-beyond-react-16.html). Now you can use the Suspense component to do [code-splitting](/docs/code-splitting.html#reactlazy) by wrapping a dynamic import in a call to `React.lazy()`. +Возможно, вы уже видели [доклад Дэна о React Suspense(задержке) на JSConf Iceland](/blog/2018/03/01/sneak-peek-beyond-react-16.html). Теперь можно использовать компонент Suspense для [разделения кода](/docs/code-splitting.html#reactlazy) -- нужно просто обернуть динамический импорт в `React.lazy()`. ```js import React, {lazy, Suspense} from 'react'; @@ -27,33 +27,33 @@ const OtherComponent = lazy(() => import('./OtherComponent')); function MyComponent() { return ( - Loading...}> + Загрузка...}> ); } ``` -The Suspense component will also allow library authors to start building data fetching with Suspense support in the future. +Компонент Suspense также даст возможность авторам библиотек в дальнейшем реализовать подгрузку данных с задержкой. -> Note: This feature is not yet available for server-side rendering. Suspense support will be added in a later release. +> Примечание: эта функциональность пока не доступна для серверного рендеринга. Задержка будет добавлена в будущих релизах. ## [`static contextType`](/docs/context.html#classcontexttype) {#static-contexttype} -In [React 16.3](/blog/2018/03/29/react-v-16-3.html) we introduced the official Context API as a replacement to the previous [Legacy Context](/docs/legacy-context.html) API. +В [React 16.3](/blog/2018/03/29/react-v-16-3.html) мы представили официальный API для контекста, который заменит [устаревший](/docs/legacy-context.html). ```js const MyContext = React.createContext(); ``` -We've heard feedback that adopting the new render prop API can be difficult in class components. So we've added a convenience API to [consume a context value from within a class component](/docs/context.html#classcontexttype). +Мы учли отзывы про сложности использования нового API рендер-пропсов в классовых компонентах. Поэтому добавили удобный API для [получения значений контекста из классовых компонентов](/docs/context.html#classcontexttype). ```js class MyClass extends React.Component { static contextType = MyContext; componentDidMount() { let value = this.context; - /* perform a side-effect at mount using the value of MyContext */ + /* выполнить побочный эффект при монтировании, взяв значение из MyContext */ } componentDidUpdate() { let value = this.context; @@ -65,88 +65,87 @@ class MyClass extends React.Component { } render() { let value = this.context; - /* render something based on the value of MyContext */ + /* отрендерить что-нибудь, основываясь на значении из контекста */ } } ``` ## [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) {#static-getderivedstatefromerror} -React 16 introduced [Error Boundaries](/blog/2017/07/26/error-handling-in-react-16.html) for handling errors thrown in React renders. We already had the `componentDidCatch` lifecycle method which gets fired after an error has already happened. It's great for logging errors to the server. It also lets you show a different UI to the user by calling `setState`. +React 16 впервые представил [предохранители](/blog/2017/07/26/error-handling-in-react-16.html) -- механизм обработки ошибок, выброшенных при рендере. У нас уже есть метод жизненного цикла, вызываемый после возникновения ошибок, -- `componentDidCatch` -- он отлично подходит для отправки логов ошибок на сервер. Плюс к этому, с его помощью можно вызвать `setState` и показать другой UI. -Before that is fired, we render `null` in place of the tree that threw an error. This sometimes breaks parent components that don't expect their refs to be empty. It also doesn't work to recover from errors on the server since the `Did` lifecycle methods don't fire during server-side rendering. +До вызова этого метода мы рендерим `null` в точке дерева, где произошла ошибка. Иногда родительские компоненты бывают не готовы к исчезновению рефов на дочерние компоненты и ломаются. Восстановиться после ошибки на сервере также нельзя, потому что `Did`-методы жизненного цикла при серверном рендере не вызываются. -We're adding another error method that lets you render the fallback UI before the render completes. See the docs for [`getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror). +Мы добавили новый метод для рендера запасного UI до момента, пока не завершится полный рендер. Подробнее о [`getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) вы можете почитать в документации. -> Note: `getDerivedStateFromError()` is not yet available for server-side rendering. It is designed to work with server-side rendering in a future release. We're releasing it early so that you can start preparing to use it. +> Примечание: `getDerivedStateFromError()` пока что не работает в серверном рендере. Мы выпустили его в таком сыром виде, чтобы вы пораньше с ним освоились и подготовились к релизу, в котором метод заработает и на сервере. -## Deprecations in StrictMode {#deprecations-in-strictmode} +## Устаревшие API в StrictMode {#deprecations-in-strictmode} -In [16.3](/blog/2018/03/29/react-v-16-3.html#strictmode-component) we introduced the [`StrictMode`](/docs/strict-mode.html) component. It lets you opt-in to early warnings for patterns that might cause problems in the future. +В [версии 16.3](/blog/2018/03/29/react-v-16-3.html#strictmode-component) мы представили компонент [`StrictMode`](/docs/strict-mode.html), который позволяет выводить предупреждения, если в коде используются конструкции, которые в будущем могут вызвать проблемы. -We've added two more APIs to the list of deprecated APIs in `StrictMode`. If you don't use `StrictMode` you don't have to worry; these warning won't fire for you. +Мы добавили ещё два API в список устаревших API `StrictMode`. Не беспокойтесь: если вы не используете `StrictMode`, эти предупреждения у вас не появятся. -* __ReactDOM.findDOMNode()__ - This API is often misunderstood and most uses of it are unnecessary. It can also be surprisingly slow in React 16. [See the docs](/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) for possible upgrade paths. -* __Legacy Context__ using contextTypes and getChildContext - Legacy context makes React slightly slower and bigger than it needs to be. That's why we strongly want to encourage upgrading to the [new context API](/docs/context.html). Hopefully the addition of the [`contextType`](/docs/context.html#classcontexttype) API makes this a bit easier. +* __ReactDOM.findDOMNode()__ -- этот API-метод часто неправильно понимают, и в большинстве случаев он не нужен. К тому же, он может сильно тормозить в React 16. В [документации](/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) мы описали, чем можно его заменить. +* __Legacy Context__ -- contextTypes и getChildContext слегка замедляют React и добавляют ему лишней громоздкости. Так что мы настоятельно рекомендуем вам перейти на [новый API контекста](/docs/context.html). Мы надеемся, что новый API [`contextType`](/docs/context.html#classcontexttype) упростит вам переход. -If you're having trouble upgrading, we'd like to hear your feedback. +Если у вас возникнут трудности с обновлением, пожалуйста, дайте нам знать. -## Installation {#installation} +## Установка {#installation} -React v16.6.0 is available on the npm registry. +React v16.6.0 уже доступен в реестре npm. -To install React 16 with Yarn, run: +Чтобы установить React 16 при помощи yarn, запустите: ```bash yarn add react@^16.6.0 react-dom@^16.6.0 ``` -To install React 16 with npm, run: +Чтобы установить React 16 при помощи npm, запустите: ```bash npm install --save react@^16.6.0 react-dom@^16.6.0 ``` -We also provide UMD builds of React via a CDN: +Также мы даём возможность скачивать UMD-сборки React через CDN: ```html ``` -Refer to the documentation for [detailed installation instructions](/docs/installation.html). +[Подробнее об установке](/docs/installation.html) вы можете узнать в документации. -## Changelog {#changelog} +## Список изменений {#changelog} ### React {#react} -* Add `React.memo()` as an alternative to `PureComponent` for functions. ([@acdlite](https://github.com/acdlite) in [#13748](https://github.com/facebook/react/pull/13748)) -* Add `React.lazy()` for code splitting components. ([@acdlite](https://github.com/acdlite) in [#13885](https://github.com/facebook/react/pull/13885)) -* `React.StrictMode` now warns about legacy context API. ([@bvaughn](https://github.com/bvaughn) in [#13760](https://github.com/facebook/react/pull/13760)) -* `React.StrictMode` now warns about `findDOMNode`. ([@sebmarkbage](https://github.com/sebmarkbage) in [#13841](https://github.com/facebook/react/pull/13841)) -* Rename `unstable_AsyncMode` to `unstable_ConcurrentMode`. ([@trueadm](https://github.com/trueadm) in [#13732](https://github.com/facebook/react/pull/13732)) -* Rename `unstable_Placeholder` to `Suspense`, and `delayMs` to `maxDuration`. ([@gaearon](https://github.com/gaearon) in [#13799](https://github.com/facebook/react/pull/13799) and [@sebmarkbage](https://github.com/sebmarkbage) in [#13922](https://github.com/facebook/react/pull/13922)) +* Добавлен `React.memo()` в качестве альтернативы `PureComponent` для функциональных компонентов. ([@acdlite](https://github.com/acdlite) в [#13748](https://github.com/facebook/react/pull/13748)) +* Добавлен `React.lazy()` для компонентов с разделением кода. ([@acdlite](https://github.com/acdlite) в [#13885](https://github.com/facebook/react/pull/13885)) +* `React.StrictMode` теперь предупреждает об устаревшем API контекста. ([@bvaughn](https://github.com/bvaughn) в [#13760](https://github.com/facebook/react/pull/13760)) +* `React.StrictMode` теперь предупреждает о `findDOMNode`. ([@sebmarkbage](https://github.com/sebmarkbage) в [#13841](https://github.com/facebook/react/pull/13841)) +* `unstable_AsyncMode` переименован в `unstable_ConcurrentMode`. ([@trueadm](https://github.com/trueadm) в [#13732](https://github.com/facebook/react/pull/13732)) +* `unstable_Placeholder` переименован в `Suspense`, а `delayMs` -- в `maxDuration`. ([@gaearon](https://github.com/gaearon) в [#13799](https://github.com/facebook/react/pull/13799) и [@sebmarkbage](https://github.com/sebmarkbage) в [#13922](https://github.com/facebook/react/pull/13922)) ### React DOM {#react-dom} -* Add `contextType` as a more ergonomic way to subscribe to context from a class. ([@bvaughn](https://github.com/bvaughn) in [#13728](https://github.com/facebook/react/pull/13728)) -* Add `getDerivedStateFromError` lifecycle method for catching errors in a future asynchronous server-side renderer. ([@bvaughn](https://github.com/bvaughn) in [#13746](https://github.com/facebook/react/pull/13746)) -* Warn when `` is used instead of ``. ([@trueadm](https://github.com/trueadm) in [#13829](https://github.com/facebook/react/pull/13829)) -* Fix gray overlay on iOS Safari. ([@philipp-spiess](https://github.com/philipp-spiess) in [#13778](https://github.com/facebook/react/pull/13778)) -* Fix a bug caused by overwriting `window.event` in development. ([@sergei-startsev](https://github.com/sergei-startsev) in [#13697](https://github.com/facebook/react/pull/13697)) +* Добавлен более удобный способ подписки на контекст из классов -- `contextType`. ([@bvaughn](https://github.com/bvaughn) в [#13728](https://github.com/facebook/react/pull/13728)) +* Добавлен метод жизненного цикла для отлова ошибок в новом асинхронном серверном рендерере `getDerivedStateFromError`. ([@bvaughn](https://github.com/bvaughn) в [#13746](https://github.com/facebook/react/pull/13746)) +* Теперь выводится предупреждение, когда вместо `` используется ``. ([@trueadm](https://github.com/trueadm) в [#13829](https://github.com/facebook/react/pull/13829)) +* Исправлен серый оверлей в iOS Safari. ([@philipp-spiess](https://github.com/philipp-spiess) в [#13778](https://github.com/facebook/react/pull/13778)) +* Исправлен баг, вызываемый перезаписью `window.event` в режиме разработки. ([@sergei-startsev](https://github.com/sergei-startsev) в [#13697](https://github.com/facebook/react/pull/13697)) ### React DOM Server {#react-dom-server} -* Add support for `React.memo()`. ([@alexmckenley](https://github.com/alexmckenley) in [#13855](https://github.com/facebook/react/pull/13855)) -* Add support for `contextType`. ([@alexmckenley](https://github.com/alexmckenley) and [@sebmarkbage](https://github.com/sebmarkbage) in [#13889](https://github.com/facebook/react/pull/13889)) +* Добавлена поддержка `React.memo()`. ([@alexmckenley](https://github.com/alexmckenley) в [#13855](https://github.com/facebook/react/pull/13855)) +* Добавлена поддержка `contextType`. ([@alexmckenley](https://github.com/alexmckenley) и [@sebmarkbage](https://github.com/sebmarkbage) в [#13889](https://github.com/facebook/react/pull/13889)) -### Scheduler (Experimental) {#scheduler-experimental} - -* Rename the package to `scheduler`. ([@gaearon](https://github.com/gaearon) in [#13683](https://github.com/facebook/react/pull/13683)) -* Support priority levels, continuations, and wrapped callbacks. ([@acdlite](https://github.com/acdlite) in [#13720](https://github.com/facebook/react/pull/13720) and [#13842](https://github.com/facebook/react/pull/13842)) -* Improve the fallback mechanism in non-DOM environments. ([@acdlite](https://github.com/acdlite) in [#13740](https://github.com/facebook/react/pull/13740)) -* Schedule `requestAnimationFrame` earlier. ([@acdlite](https://github.com/acdlite) in [#13785](https://github.com/facebook/react/pull/13785)) -* Fix the DOM detection to be more thorough. ([@trueadm](https://github.com/trueadm) in [#13731](https://github.com/facebook/react/pull/13731)) -* Fix bugs with interaction tracing. ([@bvaughn](https://github.com/bvaughn) in [#13590](https://github.com/facebook/react/pull/13590)) -* Add the `envify` transform to the package. ([@mridgway](https://github.com/mridgway) in [#13766](https://github.com/facebook/react/pull/13766)) +### Планировщик (экспериментально) {#scheduler-experimental} +* Пакет переименован в `scheduler`. ([@gaearon](https://github.com/gaearon) в [#13683](https://github.com/facebook/react/pull/13683)) +* Добавлена поддержка продолжений, обёрнутых колбэков и уровней приоритета. ([@acdlite](https://github.com/acdlite) в [#13720](https://github.com/facebook/react/pull/13720) и [#13842](https://github.com/facebook/react/pull/13842)) +* Улучшен механизм запасного планировщика в среде без DOM. ([@acdlite](https://github.com/acdlite) в [#13740](https://github.com/facebook/react/pull/13740)) +* `requestAnimationFrame` теперь принудительно выполняется в начале фрейма. ([@acdlite](https://github.com/acdlite) в [#13785](https://github.com/facebook/react/pull/13785)) +* Добавлена более тщательная проверка на наличие DOM. ([@trueadm](https://github.com/trueadm) в [#13731](https://github.com/facebook/react/pull/13731)) +* Исправлены баги счётчика взамодействий. ([@bvaughn](https://github.com/bvaughn) в [#13590](https://github.com/facebook/react/pull/13590)) +* В пакет добавлена `envify`-трансформация кода. ([@mridgway](https://github.com/mridgway) in [#13766](https://github.com/facebook/react/pull/13766))