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
Copy file name to clipboardExpand all lines: content/docs/hooks-faq.md
+8-65Lines changed: 8 additions & 65 deletions
Original file line number
Diff line number
Diff line change
@@ -18,7 +18,6 @@ prev: hooks-reference.html
18
18
).join('\n')
19
19
-->
20
20
21
-
<<<<<<< HEAD
22
21
*[Внедрение хуков](#adoption-strategy)
23
22
*[В какой версии React появились хуки?](#which-versions-of-react-include-hooks)
24
23
*[Нужно ли переписать все мои классовые компоненты?](#do-i-need-to-rewrite-all-my-class-components)
@@ -62,52 +61,6 @@ prev: hooks-reference.html
62
61
### В какой версии React появились хуки? {#which-versions-of-react-include-hooks}
63
62
64
63
Начиная с релиза 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
64
112
65
* React DOM
113
66
* React DOM Server
@@ -498,15 +451,11 @@ function ScrollView({row}) {
498
451
499
452
### Могу ли я изменить реф, переданный в функциональный компонент? {#can-i-make-a-ref-to-a-function-component}
500
453
501
-
502
454
Несмотря на то, что вам не понадобится это часто, вы можете предоставить некоторые императивные методы родительскому компоненту, используя хук [`useImperativeHandle`](/docs/hooks-reference.html#useimperativehandle).
503
455
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}
456
+
### Как я могу измерить узел DOM? {#how-can-i-measure-a-dom-node}
508
457
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):
458
+
Для измерения положения или размера узла DOM можно использовать [реф-колбек](/docs/refs-and-the-dom.html#callback-refs). React будет вызывать этот колбэк всякий раз, когда ref подключается к другому узлу. Вот [небольшая демонстрация](https://codesandbox.io/s/l7m0v5x4v9):
510
459
511
460
```js{4-8,12}
512
461
function MeasureExample() {
@@ -520,18 +469,18 @@ function MeasureExample() {
520
469
521
470
return (
522
471
<>
523
-
<h1 ref={measuredRef}>Hello, world</h1>
524
-
<h2>The above header is {Math.round(height)}px tall</h2>
472
+
<h1 ref={measuredRef}>Привет, мир</h1>
473
+
<h2>Заголовок выше {Math.round(height)} пикселей в высоту</h2>
525
474
</>
526
475
);
527
476
}
528
477
```
529
478
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.
479
+
Мы не выбрали`useRef`в этом примере, потому что объект рефа не уведомляет нас об *изменениях* текущего значения рефа. Использование колбэк-рефа гарантирует, что [даже если дочерний компонент отображает измеренный узел позже](https://codesandbox.io/s/818zzk8m78) (например, в ответ на клик), мы по-прежнему получаем уведомление об этом в родительском компоненте и можем обновлять измерения.
531
480
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.
481
+
Обратите внимание, что мы передаем `[]`как массив зависимостей в `useCallback`. Это гарантирует, что наш обратный вызов рефа не изменится между повторными рендерами, и поэтому React не вызовет его без необходимости.
533
482
534
-
If you want, you can [extract this logic](https://codesandbox.io/s/m5o42082xy)into a reusable Hook:
483
+
При желании вы можете [извлечь эту логику](https://codesandbox.io/s/m5o42082xy)в многоразовый хук:
535
484
536
485
```js{2}
537
486
function MeasureExample() {
@@ -558,8 +507,7 @@ function useClientRect() {
558
507
```
559
508
560
509
561
-
### What does `const [thing, setThing] = useState()` mean? {#what-does-const-thing-setthing--usestate-mean}
562
-
>>>>>>> 1f2dbb7a4f531d1c9d70ae69e025eac992b37c6a
510
+
### Что значит `const [thing, setThing] = useState()`? {#what-does-const-thing-setthing--usestate-mean}
563
511
564
512
Если вы не знакомы с этим синтаксисом, ознакомьтесь с [объяснением](/docs/hooks-state.html#tip-what-do-square-brackets-mean) в документации хука состояния.
Copy file name to clipboardExpand all lines: content/docs/hooks-reference.md
+15-27Lines changed: 15 additions & 27 deletions
Original file line number
Diff line number
Diff line change
@@ -176,29 +176,25 @@ useEffect(
176
176
constvalue=useContext(MyContext);
177
177
```
178
178
179
-
<<<<<<< HEAD
180
-
Принимает объект контекста (значение, возвращённое из `React.createContext`) и возвращает текущее значение контекста, как указано ближайшим поставщиком контекста для данного контекста.
181
-
182
-
Когда провайдер обновляется, этот хук инициирует повторный рендер с последним значением контекста.
183
-
=======
184
-
Accepts a context object (the value returned from `React.createContext`) and returns the current context value for that context. The current context value is determined by the `value` prop of the nearest `<MyContext.Provider>` above the calling component in the tree.
179
+
Принимает объект контекста (значение, возвращаемое из `React.createContext`) и возвращает текущее значение контекста для этого контекста. Текущее значение контекста определяется пропом `value` ближайшего `<MyContext.Provider>` над вызывающим компонентом в дереве.
185
180
186
181
When the nearest `<MyContext.Provider>` above the component updates, this Hook will trigger a rerender with the latest context `value` passed to that `MyContext` provider.
182
+
Когда ближайший `<MyContext.Provider>`находится над обновлениями компонентов этот хук вызовет повторный рендер с последним значением контекста, переданным этому поставщику `MyContext`.
187
183
188
-
Don't forget that the argument to `useContext`must be the *context object itself*:
184
+
Не забывайте, что аргумент `useContext`должен быть самим объектом *context*:
189
185
190
186
***Correct:**`useContext(MyContext)`
191
187
***Incorrect:**`useContext(MyContext.Consumer)`
192
188
***Incorrect:**`useContext(MyContext.Provider)`
193
189
194
-
A component calling `useContext`will always re-render when the context value changes. If re-rendering the component is expensive, you can [optimize it by using memoization](https://github.com/facebook/react/issues/15156#issuecomment-474590693).
190
+
Компонент вызывае `useContext`всегда будет перерендерится при изменении контекста значение. При повторной визуализации компонент стоит дорого, вы можете [оптимизировать его с помощью мемоизации](https://github.com/facebook/react/issues/15156#issuecomment-474590693).
195
191
196
-
>Tip
192
+
>Подсказка
197
193
>
198
194
>If you're familiar with the context API before Hooks, `useContext(MyContext)` is equivalent to `static contextType = MyContext` in a class, or to `<MyContext.Consumer>`.
195
+
>Если вы знакомы с контекстным API до хуков, `useContext(MyContext)` эквивалентно `static contextType = MyContext` в классе или `<MyContext.Provider`.
199
196
>
200
-
>`useContext(MyContext)` only lets you *read* the context and subscribe to its changes. You still need a `<MyContext.Provider>` above in the tree to *provide* the value for this context.
201
-
>>>>>>> 1f2dbb7a4f531d1c9d70ae69e025eac992b37c6a
197
+
>useContext (MyContext)` позволяет только *читать* контекст и подписываться на его изменения. Вам все еще нужен `<MyContext.Provider>` выше в дереве ,чтобы *предоставить* значение для этого контекста.
202
198
203
199
## Дополнительные хуки {#additional-hooks}
204
200
@@ -378,20 +374,16 @@ function TextInputWithFocusButton() {
378
374
}
379
375
```
380
376
381
-
<<<<<<< HEAD
382
-
Обратите внимание, что `useRef()` полезен не только для атрибута `ref`. Он также [удобен для хранения любого изменяемого значения](/docs/hooks-faq.html#is-there-something-like-instance-variables) примерно так же, как вы используете поля экземпляров в классах.
383
-
=======
384
-
Essentially, `useRef` is like a "box" that can hold a mutable value in its `.current` property.
377
+
По сути, `useRef` - это как «коробка», которая может содержать изменяемое значение в своем `текущем` свойстве.
385
378
386
-
You might be familiar with refs primarily as a way to [access the DOM](/docs/refs-and-the-dom.html). If you pass a ref object to React with `<div ref={myRef}/>`, React will set its `.current`property to the corresponding DOM node whenever that node changes.
379
+
Вы можете быть знакомы с рефами в первую очередь как со способом [access the DOM](/docs/refs-and-the-dom.html). Если вы передадите объект рефа для реакции с `<div ref={myRef}/>`, React установит его `.current`текущим для соответствующего узла DOM при каждом изменении этого узла.
387
380
388
-
However,`useRef()`is useful for more than the `ref` attribute. It's [handy for keeping any mutable value around](/docs/hooks-faq.html#is-there-something-like-instance-variables)similar to how you'd use instance fields in classes.
381
+
Однако`useRef()`полезен не только для атрибута реф. Это [удобно для сохранения любого изменяемого значения](/docs/hooks-faq.html#is-there-something-like-instance-variables)аналогично тому, как вы бы использовали поля экземпляра в классах.
389
382
390
-
This works because `useRef()`creates a plain JavaScript object. The only difference between `useRef()`and creating a `{current:...}` object yourself is that `useRef`will give you the same ref object on every render.
383
+
Это работает, потому что `useRef()`создает простой объект JavaScript. Единственное различие между `useRef()`и созданием`{current:...}`сам объект заключается в том, что `useRef`даст вам один и тот же объект реф для каждого рендеринга.
391
384
392
-
Keep in mind that`useRef`*doesn't* notify you when its content changes. Mutating the`.current`property doesn't cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a [callback ref](/docs/hooks-faq.html#how-can-i-measure-a-dom-node)instead.
385
+
Имейте в виду, что`useRef`*не уведомляет вас, когда изменяется его содержимое. Мутация свойство`.current`не вызывает повторной визуализации. Если вы хотите запустить некоторый код, когда React присоединяет или отсоединяет реф к узлу DOM, вы можете использовать [колбек рефа](/docs/hooks-faq.html#how-can-i-measure-a-dom-node)вместо этого.
> Если вы переносите код из классового компонента, `useLayoutEffect` запускается в той же фазе, что и `componentDidMount` и `componentDidUpdate`, поэтому, если вы не уверены, какой хук эффект использовать, это, вероятно, наименее рискованно.
429
-
=======
430
-
> If you're migrating code from a class component, note `useLayoutEffect` fires in the same phase as `componentDidMount` and `componentDidUpdate`. However, **we recommend starting with `useEffect` first** and only trying `useLayoutEffect` if that causes a problem.
419
+
> Если вы переносите код из классового компонента, `useLayoutEffect` запускается в той же фазе, что и `componentDidMount` и `componentDidUpdate`. Однако, *мы рекомендуем начать вначале с `useEffect`** и только попробовать `useLayoutEffect`, если это вызывает проблему.
431
420
>
432
-
>If you use server rendering, keep in mind that *neither*`useLayoutEffect` nor`useEffect`can run until the JavaScript is downloaded. This is why React warns when a server-rendered component contains `useLayoutEffect`. To fix this, either move that logic to`useEffect` (if it isn't necessary for the first render), or delay showing that component until after the client renders (if the HTML looks broken until `useLayoutEffect` runs).
421
+
>Если вы используете серверный рендер, имейте в виду, что *ни*`useLayoutEffect`, ни`useEffect`не могут работать до загрузки JavaScript. Вот почему React предупреждает, когда серверный компонент содержит `useLayoutEffect`. Чтобы исправить это, либо переместите эту логику в`useEffect` (если это не необходимо для первого рендера), либо задержите показ этого компонента до тех пор, пока клиент не отрисовает (если HTML выглядит сломанным до запуска `useLayoutEffect`).
433
422
>
434
-
>To exclude a component that needs layout effects from the server-rendered HTML, render it conditionally with `showChild && <Child />` and defer showing it with `useEffect(() => { setShowChild(true); }, [])`. This way, the UI doesn't appear broken before hydration.
435
-
>>>>>>> 1f2dbb7a4f531d1c9d70ae69e025eac992b37c6a
423
+
>Чтобы исключить компонент, который нуждается в эффектах макета из HTML-кода, отображаемого сервером, сделайте его условно с помощью `showChild & & <Child / >` и отложите показ с помощью ` useEffect(() => { setShowChild(true);}, [])`. Таким образом, пользовательский интерфейс не отображается сломанным перед гидратацией.
0 commit comments