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
*[Могу ли я пропустить эффект при обновлениях?](#can-i-skip-an-effect-on-updates)
@@ -62,52 +62,6 @@ prev: hooks-reference.html
62
62
### В какой версии React появились хуки? {#which-versions-of-react-include-hooks}
63
63
64
64
Начиная с релиза 16.8.0, React включает в себя стабильную реализацию хуков для:
65
-
=======
66
-
***[Adoption Strategy](#adoption-strategy)**
67
-
*[Which versions of React include Hooks?](#which-versions-of-react-include-hooks)
68
-
*[Do I need to rewrite all my class components?](#do-i-need-to-rewrite-all-my-class-components)
69
-
*[What can I do with Hooks that I couldn't with classes?](#what-can-i-do-with-hooks-that-i-couldnt-with-classes)
70
-
*[How much of my React knowledge stays relevant?](#how-much-of-my-react-knowledge-stays-relevant)
71
-
*[Should I use Hooks, classes, or a mix of both?](#should-i-use-hooks-classes-or-a-mix-of-both)
72
-
*[Do Hooks cover all use cases for classes?](#do-hooks-cover-all-use-cases-for-classes)
73
-
*[Do Hooks replace render props and higher-order components?](#do-hooks-replace-render-props-and-higher-order-components)
74
-
*[What do Hooks mean for popular APIs like Redux connect() and React Router?](#what-do-hooks-mean-for-popular-apis-like-redux-connect-and-react-router)
75
-
*[Do Hooks work with static typing?](#do-hooks-work-with-static-typing)
76
-
*[How to test components that use Hooks?](#how-to-test-components-that-use-hooks)
77
-
*[What exactly do the lint rules enforce?](#what-exactly-do-the-lint-rules-enforce)
78
-
***[From Classes to Hooks](#from-classes-to-hooks)**
79
-
*[How do lifecycle methods correspond to Hooks?](#how-do-lifecycle-methods-correspond-to-hooks)
80
-
*[How can I do data fetching with Hooks?](#how-can-i-do-data-fetching-with-hooks)
81
-
*[Is there something like instance variables?](#is-there-something-like-instance-variables)
82
-
*[Should I use one or many state variables?](#should-i-use-one-or-many-state-variables)
83
-
*[Can I run an effect only on updates?](#can-i-run-an-effect-only-on-updates)
84
-
*[How to get the previous props or state?](#how-to-get-the-previous-props-or-state)
85
-
*[Why am I seeing stale props or state inside my function?](#why-am-i-seeing-stale-props-or-state-inside-my-function)
86
-
*[How do I implement getDerivedStateFromProps?](#how-do-i-implement-getderivedstatefromprops)
87
-
*[Is there something like forceUpdate?](#is-there-something-like-forceupdate)
88
-
*[Can I make a ref to a function component?](#can-i-make-a-ref-to-a-function-component)
89
-
*[How can I measure a DOM node?](#how-can-i-measure-a-dom-node)
90
-
*[What does const [thing, setThing] = useState() mean?](#what-does-const-thing-setthing--usestate-mean)
*[Can I skip an effect on updates?](#can-i-skip-an-effect-on-updates)
93
-
*[Is it safe to omit functions from the list of dependencies?](#is-it-safe-to-omit-functions-from-the-list-of-dependencies)
94
-
*[What can I do if my effect dependencies change too often?](#what-can-i-do-if-my-effect-dependencies-change-too-often)
95
-
*[How do I implement shouldComponentUpdate?](#how-do-i-implement-shouldcomponentupdate)
96
-
*[How to memoize calculations?](#how-to-memoize-calculations)
97
-
*[How to create expensive objects lazily?](#how-to-create-expensive-objects-lazily)
98
-
*[Are Hooks slow because of creating functions in render?](#are-hooks-slow-because-of-creating-functions-in-render)
99
-
*[How to avoid passing callbacks down?](#how-to-avoid-passing-callbacks-down)
100
-
*[How to read an often-changing value from useCallback?](#how-to-read-an-often-changing-value-from-usecallback)
101
-
***[Under the Hood](#under-the-hood)**
102
-
*[How does React associate Hook calls with components?](#how-does-react-associate-hook-calls-with-components)
103
-
*[What is the prior art for Hooks?](#what-is-the-prior-art-for-hooks)
104
-
105
-
## Adoption Strategy {#adoption-strategy}
106
-
107
-
### Which versions of React include Hooks? {#which-versions-of-react-include-hooks}
108
-
109
-
Starting with 16.8.0, React includes a stable implementation of React Hooks for:
110
-
>>>>>>> 1f2dbb7a4f531d1c9d70ae69e025eac992b37c6a
111
65
112
66
* React DOM
113
67
* React DOM Server
@@ -450,7 +404,7 @@ function Example() {
450
404
451
405
Если вы намеренно хотите считать из асинхронного колбэка *свежайшее* состояние, вы можете сперва сохранить его [в реф](/docs/hooks-faq.html#is-there-something-like-instance-variables), потом изменить его и затем считать его из рефа.
452
406
453
-
Наконец, возможна другая ситуация, почему вы видите устаревшие пропсы или состояние: когда вы используете оптимизацию с помощью «массива зависимостей», но неправильно указали какие-то зависимости. Например, если эффект передаёт вторым параметром `[]`, но при этом использует `someProp`, то он продолжит «видеть» исходное значение `someProp`. Правильным решением является либо исправление массива, либо отказ от его использования.
407
+
Наконец, возможна другая ситуация, почему вы видите устаревшие пропсы или состояние: когда вы используете оптимизацию с помощью «массива зависимостей», но неправильно указали какие-то зависимости. Например, если эффект передаёт вторым параметром `[]`, но при этом использует `someProp`, то он продолжит «видеть» исходное значение `someProp`. Правильным решением является либо исправление массива, либо отказ от его использования.
454
408
По этим ссылкам описаны [подходы к функциям](#is-it-safe-to-omit-functions-from-the-list-of-dependencies) в аналогичных ситуациях и [другие известные способы](#what-can-i-do-if-my-effect-dependencies-change-too-often) снижения частоты вызова эффектов, исключающие передачу неправильных зависимостей.
455
409
456
410
>Примечание
@@ -498,15 +452,11 @@ function ScrollView({row}) {
498
452
499
453
### Могу ли я изменить реф, переданный в функциональный компонент? {#can-i-make-a-ref-to-a-function-component}
500
454
501
-
502
455
Несмотря на то, что вам не понадобится это часто, вы можете предоставить некоторые императивные методы родительскому компоненту, используя хук [`useImperativeHandle`](/docs/hooks-reference.html#useimperativehandle).
503
456
504
-
<<<<<<< HEAD
505
-
### Что значит `const [thing, setThing] = useState()`? {#what-does-const-thing-setthing--usestate-mean}
506
-
=======
507
-
### How can I measure a DOM node? {#how-can-i-measure-a-dom-node}
457
+
### Как я могу измерить узел DOM? {#how-can-i-measure-a-dom-node}
508
458
509
-
In order to measure the position or size of a DOM node, you can use a [callback ref](/docs/refs-and-the-dom.html#callback-refs). React will call that callback whenever the ref gets attached to a different node. Here is a [small demo](https://codesandbox.io/s/l7m0v5x4v9):
459
+
Для измерения положения или размера узла DOM можно использовать [колбэк-реф](/docs/refs-and-the-dom.html#callback-refs). React будет вызывать этот колбэк всякий раз, когда ref подключается к другому узлу. Вот [небольшая демонстрация](https://codesandbox.io/s/l7m0v5x4v9):
510
460
511
461
```js{4-8,12}
512
462
function MeasureExample() {
@@ -520,18 +470,18 @@ function MeasureExample() {
520
470
521
471
return (
522
472
<>
523
-
<h1 ref={measuredRef}>Hello, world</h1>
524
-
<h2>The above header is {Math.round(height)}px tall</h2>
473
+
<h1 ref={measuredRef}>Привет, мир</h1>
474
+
<h2>Заголовок выше {Math.round(height)} пикселей в высоту</h2>
525
475
</>
526
476
);
527
477
}
528
478
```
529
479
530
-
We didn't choose`useRef`in this example because an object ref doesn't notify us about *changes* to the current ref value. Using a callback ref ensures that [even if a child component displays the measured node later](https://codesandbox.io/s/818zzk8m78) (e.g. in response to a click), we still get notified about it in the parent component and can update the measurements.
480
+
Мы не выбрали`useRef`в этом примере, потому что объект рефа не уведомляет нас об *изменениях* текущего значения рефа. Использование колбэк-рефа гарантирует, что [даже если дочерний компонент отображает измеренный узел позже](https://codesandbox.io/s/818zzk8m78) (например, в ответ на клик), мы по-прежнему получаем уведомление об этом в родительском компоненте и можем обновлять измерения.
531
481
532
-
Note that we pass `[]`as a dependency array to `useCallback`. This ensures that our ref callback doesn't change between the re-renders, and so React won't call it unnecessarily.
482
+
Обратите внимание, что мы передаем `[]`как массив зависимостей в `useCallback`. Это гарантирует, что наш обратный вызов рефа не изменится между повторными рендерами, и поэтому React не вызовет его без необходимости.
533
483
534
-
If you want, you can [extract this logic](https://codesandbox.io/s/m5o42082xy)into a reusable Hook:
484
+
При желании вы можете [извлечь эту логику](https://codesandbox.io/s/m5o42082xy)в многоразовый хук:
535
485
536
486
```js{2}
537
487
function MeasureExample() {
@@ -558,8 +508,7 @@ function useClientRect() {
558
508
```
559
509
560
510
561
-
### What does `const [thing, setThing] = useState()` mean? {#what-does-const-thing-setthing--usestate-mean}
562
-
>>>>>>> 1f2dbb7a4f531d1c9d70ae69e025eac992b37c6a
511
+
### Что значит `const [thing, setThing] = useState()`? {#what-does-const-thing-setthing--usestate-mean}
563
512
564
513
Если вы не знакомы с этим синтаксисом, ознакомьтесь с [объяснением](/docs/hooks-state.html#tip-what-do-square-brackets-mean) в документации хука состояния.
0 commit comments