Skip to content

Commit 7da7d1a

Browse files
committed
Remove comments & fix stylistics
1 parent cf5aef0 commit 7da7d1a

File tree

1 file changed

+11
-54
lines changed

1 file changed

+11
-54
lines changed

content/blog/2018-10-23-react-v-16-6.md

Lines changed: 11 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,23 @@ title: "React v16.6.0: lazy, memo и contextType"
33
author: [sebmarkbage]
44
---
55

6-
Сегодня мы выпускаем React 16.6 с новым удобным функционаломЖ версию PureComponent/shouldComponentUpdate для функциональных компонентов, способ разделения кода при помощи Suspense и упрощённый доступ к контексту из классовых компонентов.
6+
Сегодня мы выпускаем React 16.6 с новым удобным функционалом: версию PureComponent/shouldComponentUpdate для функциональных компонентов, способ разделения кода при помощи Suspense и упрощённый доступ к контексту из классовых компонентов.
77

8-
<!-- 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. -->
9-
10-
Полный [список изменений](#changelog) описан далее в посте.
11-
12-
<!-- Check out the full [changelog](#changelog) below. -->
8+
Полный список изменений [описан далее в посте](#changelog).
139

1410
## [`React.memo`](/docs/react-api.html#reactmemo) {#reactmemo}
1511

16-
Классовые компоненты могут остановить рендеринг, если их пропсы не меняются, при помощи [`PureComponent`](/docs/react-api.html#reactpurecomponent) или [`shouldComponentUpdate`](/docs/react-component.html#shouldcomponentupdate). Теперь то же самое можно сделать и в функциональных компонентах, если обернуть их в [`React.memo`](/docs/react-api.html#reactmemo).
17-
18-
<!-- 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). -->
12+
Классовые компоненты могут останавливать рендер, если их пропсы не меняются, при помощи [`PureComponent`](/docs/react-api.html#reactpurecomponent) или [`shouldComponentUpdate`](/docs/react-component.html#shouldcomponentupdate). Теперь то же самое можно сделать и в функциональных компонентах, если обернуть их в [`React.memo`](/docs/react-api.html#reactmemo).
1913

2014
```js
2115
const MyComponent = React.memo(function MyComponent(props) {
2216
/* повторный рендер пройдёт только при изменении пропсов */
2317
});
2418
```
2519

26-
## [`React.lazy`](/docs/code-splitting.html#reactlazy): Разделение кода с помощью `Suspense` {#reactlazy-code-splitting-with-suspense}
27-
28-
<!-- ## [`React.lazy`](/docs/code-splitting.html#reactlazy): Code-Splitting with `Suspense` {#reactlazy-code-splitting-with-suspense} -->
29-
30-
Возможно, вы уже видели [доклад Дэна о React Suspense(задержке) на JSConf Iceland](/blog/2018/03/01/sneak-peek-beyond-react-16.html). Теперь вы можете использовать компонент Suspense для [разделения кода](/docs/code-splitting.html#reactlazy) -- просто оберните динамический импорт в `React.lazy()`.
20+
## [`React.lazy`](/docs/code-splitting.html#reactlazy): разделение кода при помощи `Suspense` {#reactlazy-code-splitting-with-suspense}
3121

32-
<!-- 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()`. -->
22+
Возможно, вы уже видели [доклад Дэна о React Suspense(задержке) на JSConf Iceland](/blog/2018/03/01/sneak-peek-beyond-react-16.html). Теперь можно использовать компонент Suspense для [разделения кода](/docs/code-splitting.html#reactlazy) -- нужно просто обернуть динамический импорт в `React.lazy()`.
3323

3424
```js
3525
import React, {lazy, Suspense} from 'react';
@@ -46,26 +36,18 @@ function MyComponent() {
4636

4737
Компонент Suspense также даст возможность авторам библиотек в дальшнейшем реализовать подгрузку данных с задержкой.
4838

49-
<!-- The Suspense component will also allow library authors to start building data fetching with Suspense support in the future. -->
50-
5139
> Примечание: этот функционал пока не доступен для серверного рендеринга. Задержка будет добавлена в более позднем релизе.
5240
53-
<!-- > Note: This feature is not yet available for server-side rendering. Suspense support will be added in a later release. -->
54-
5541
## [`static contextType`](/docs/context.html#classcontexttype) {#static-contexttype}
5642

57-
В [React 16.3](/blog/2018/03/29/react-v-16-3.html) мы представили официальный API для контекста, который заменит [устаревший API контекста](/docs/legacy-context.html).
58-
59-
<!-- 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. -->
43+
В [React 16.3](/blog/2018/03/29/react-v-16-3.html) мы представили официальный API для контекста, который заменит [устаревший](/docs/legacy-context.html).
6044

6145
```js
6246
const MyContext = React.createContext();
6347
```
6448

6549
Мы учли замечания по поводу сложностей API на базе рендер-пропсов и добавили удобный API для получения значений контекста из классовых компонентов.
6650

67-
<!-- 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). -->
68-
6951
```js
7052
class MyClass extends React.Component {
7153
static contextType = MyContext;
@@ -92,38 +74,21 @@ class MyClass extends React.Component {
9274

9375
React 16 впервые представил [предохранители](/blog/2017/07/26/error-handling-in-react-16.html) -- механизм обработки ошибок, выброшенных при рендере. У нас уже есть метод жизненного цикла, вызываемый после возникновения ошибок, -- `componentDidCatch` -- он отлично подходит для отправки логов ошибок на сервер. Плюс к этому, с его помощью можно вызвать `setState` и показать другой UI.
9476

95-
<!-- 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`. -->
96-
9777
До вызова этого метода мы рендерим `null` в точке дерева, где произошла ошибка. Иногда родительские компоненты бывают не готовы к исчезновению рефов на дочерние компоненты и ломаются. Восстановиться после ошибки на сервере также нельзя, потому что `Did`-методы жизненного цикла при серверном рендере не вызываются.
9878

99-
<!-- 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. -->
100-
101-
Мы добавили новый метод для рендера запасного UI до момента, когда завершится полный рендер. Подробне о [`getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) вы можете почитать в документации.
102-
103-
<!-- 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). -->
79+
Мы добавили новый метод для рендера запасного UI до момента, пока не завершится полный рендер. Подробнее о [`getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) вы можете почитать в документации.
10480

105-
> Примечание: `getDerivedStateFromError()` пока что не работает в серверном рендере. Мы выпустили его в таком сыром виде, чтобы вы с ним освоились и подготовились к релизу, в котором метод заработает и на сервере.
106-
107-
<!-- > 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. -->
81+
> Примечание: `getDerivedStateFromError()` пока что не работает в серверном рендере. Мы выпустили его в таком сыром виде, чтобы вы пораньше с ним освоились и подготовились к релизу, в котором метод заработает и на сервере.
10882
10983
## Устаревшие API в StrictMode {#deprecations-in-strictmode}
11084

111-
<!-- ## Deprecations in StrictMode {#deprecations-in-strictmode} -->
112-
113-
В [версии 16.3](/blog/2018/03/29/react-v-16-3.html#strictmode-component) мы представили компонент [`StrictMode`](/docs/strict-mode.html), который выводит предупреждения при использовании конструкций, которые могут вызвать проблемы в будущем.
85+
В [версии 16.3](/blog/2018/03/29/react-v-16-3.html#strictmode-component) мы представили компонент [`StrictMode`](/docs/strict-mode.html), который позволяет выводить предупреждения, если в коде используются конструкции, которые в будущем могут вызвать проблемы.
11486

115-
<!-- 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. -->
87+
Мы добавили ещё два API в список устаревших API `StrictMode`. Не беспокойтесь: если вы не используете `StrictMode`, эти предупреждения у вас не появятся.
11688

117-
Мы добавили ещё два API в список устаревших API `StrictMode`. Если вы не используете `StrictMode`, то не беспокойтесь -- эти предупреждения у вас не появятся.
118-
119-
<!-- 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. -->
120-
121-
* __ReactDOM.findDOMNode()__ -- этот API был неправильно понят и пригождается очень редко. К тому же, он может сильно тормозить в React 16. В [документации](/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) мы описали, как можно .
89+
* __ReactDOM.findDOMNode()__ -- этот API был неправильно понят и нужен очень редко. К тому же, он может сильно тормозить в React 16. В [документации](/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) мы описали, чем можно его заменить.
12290
* __Legacy Context__ -- contextTypes и getChildContext слегка замедляют React и добавляют ему лишней громоздкости. Так что мы настоятельно рекомендуем вам перейти на [новый API контекста](/docs/context.html). Мы надеемся, что новый API [`contextType`](/docs/context.html#classcontexttype) упростит вам переход.
12391

124-
<!-- * __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. -->
125-
<!-- * __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. -->
126-
12792
Если у вас возникнут трудности с обновлением, пожалуйста, дайте нам знать.
12893

12994
## Установка {#installation}
@@ -184,11 +149,3 @@ npm install --save react@^16.6.0 react-dom@^16.6.0
184149
* Добавить более тщательную проверку на наличие DOM. ([@trueadm](https://github.com/trueadm) в [#13731](https://github.com/facebook/react/pull/13731))
185150
* Пофиксить баги счётчика взамодействий. ([@bvaughn](https://github.com/bvaughn) в [#13590](https://github.com/facebook/react/pull/13590))
186151
* Добавить в пакет `envify`-трансформацию кода. ([@mridgway](https://github.com/mridgway) in [#13766](https://github.com/facebook/react/pull/13766))
187-
188-
<!-- * Rename the package to `scheduler`. ([@gaearon](https://github.com/gaearon) in [#13683](https://github.com/facebook/react/pull/13683))
189-
* 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))
190-
* Improve the fallback mechanism in non-DOM environments. ([@acdlite](https://github.com/acdlite) in [#13740](https://github.com/facebook/react/pull/13740))
191-
* Schedule `requestAnimationFrame` earlier. ([@acdlite](https://github.com/acdlite) in [#13785](https://github.com/facebook/react/pull/13785))
192-
* Fix the DOM detection to be more thorough. ([@trueadm](https://github.com/trueadm) in [#13731](https://github.com/facebook/react/pull/13731))
193-
* Fix bugs with interaction tracing. ([@bvaughn](https://github.com/bvaughn) in [#13590](https://github.com/facebook/react/pull/13590))
194-
* Add the `envify` transform to the package. ([@mridgway](https://github.com/mridgway) in [#13766](https://github.com/facebook/react/pull/13766)) -->

0 commit comments

Comments
 (0)