You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Сегодня мы выпускаем React 16.6 с новым удобным функционаломЖ версию PureComponent/shouldComponentUpdate для функциональных компонентов, способ разделения кода при помощи Suspense и упрощённый доступ к контексту из классовых компонентов.
6
+
Сегодня мы выпускаем React 16.6 с новым удобным функционалом: версию PureComponent/shouldComponentUpdate для функциональных компонентов, способ разделения кода при помощи Suspense и упрощённый доступ к контексту из классовых компонентов.
7
7
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).
Классовые компоненты могут остановить рендеринг, если их пропсы не меняются, при помощи [`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).
/* повторный рендер пройдёт только при изменении пропсов */
23
17
});
24
18
```
25
19
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}
31
21
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()`.
33
23
34
24
```js
35
25
importReact, {lazy, Suspense} from'react';
@@ -46,26 +36,18 @@ function MyComponent() {
46
36
47
37
Компонент Suspense также даст возможность авторам библиотек в дальшнейшем реализовать подгрузку данных с задержкой.
48
38
49
-
<!-- The Suspense component will also allow library authors to start building data fetching with Suspense support in the future. -->
50
-
51
39
> Примечание: этот функционал пока не доступен для серверного рендеринга. Задержка будет добавлена в более позднем релизе.
52
40
53
-
<!-- > Note: This feature is not yet available for server-side rendering. Suspense support will be added in a later release. -->
В [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).
60
44
61
45
```js
62
46
constMyContext=React.createContext();
63
47
```
64
48
65
49
Мы учли замечания по поводу сложностей API на базе рендер-пропсов и добавили удобный API для получения значений контекста из классовых компонентов.
66
50
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
-
69
51
```js
70
52
classMyClassextendsReact.Component {
71
53
static contextType = MyContext;
@@ -92,38 +74,21 @@ class MyClass extends React.Component {
92
74
93
75
React 16 впервые представил [предохранители](/blog/2017/07/26/error-handling-in-react-16.html) -- механизм обработки ошибок, выброшенных при рендере. У нас уже есть метод жизненного цикла, вызываемый после возникновения ошибок, -- `componentDidCatch` -- он отлично подходит для отправки логов ошибок на сервер. Плюс к этому, с его помощью можно вызвать `setState` и показать другой UI.
94
76
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
-
97
77
До вызова этого метода мы рендерим `null` в точке дерева, где произошла ошибка. Иногда родительские компоненты бывают не готовы к исчезновению рефов на дочерние компоненты и ломаются. Восстановиться после ошибки на сервере также нельзя, потому что `Did`-методы жизненного цикла при серверном рендере не вызываются.
98
78
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) вы можете почитать в документации.
104
80
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()` пока что не работает в серверном рендере. Мы выпустили его в таком сыром виде, чтобы вы пораньше с ним освоились и подготовились к релизу, в котором метод заработает и на сервере.
108
82
109
83
## Устаревшие API в StrictMode {#deprecations-in-strictmode}
110
84
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), который позволяет выводить предупреждения, если в коде используются конструкции, которые в будущем могут вызвать проблемы.
114
86
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`, эти предупреждения у вас не появятся.
116
88
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) мы описали, чем можно его заменить.
122
90
*__Legacy Context__ -- contextTypes и getChildContext слегка замедляют React и добавляют ему лишней громоздкости. Так что мы настоятельно рекомендуем вам перейти на [новый API контекста](/docs/context.html). Мы надеемся, что новый API [`contextType`](/docs/context.html#classcontexttype) упростит вам переход.
123
91
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
-
127
92
Если у вас возникнут трудности с обновлением, пожалуйста, дайте нам знать.
* Добавить более тщательную проверку на наличие DOM. ([@trueadm](https://github.com/trueadm) в [#13731](https://github.com/facebook/react/pull/13731))
185
150
* Пофиксить баги счётчика взамодействий. ([@bvaughn](https://github.com/bvaughn) в [#13590](https://github.com/facebook/react/pull/13590))
186
151
* Добавить в пакет `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