Skip to content

Commit a22c4b5

Browse files
authored
Merge pull request #286 from gcor/sync-1f2dbb7a
[fix] Sync with reactjs.org @ 1f2dbb7
2 parents aad51f2 + 7e502fb commit a22c4b5

File tree

2 files changed

+30
-98
lines changed

2 files changed

+30
-98
lines changed

content/docs/hooks-faq.md

+11-67
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ prev: hooks-reference.html
1818
).join('\n')
1919
-->
2020

21-
<<<<<<< HEAD
2221
* [Внедрение хуков](#adoption-strategy)
2322
* [В какой версии React появились хуки?](#which-versions-of-react-include-hooks)
2423
* [Нужно ли переписать все мои классовые компоненты?](#do-i-need-to-rewrite-all-my-class-components)
@@ -42,6 +41,7 @@ prev: hooks-reference.html
4241
* [Как я могу реализовать `getDerivedStateFromProps`?](#how-do-i-implement-getderivedstatefromprops)
4342
* [Существует что-нибудь наподобие forceUpdate?](#is-there-something-like-forceupdate)
4443
* [Могу ли я изменить реф, переданный в функциональный компонент?](#can-i-make-a-ref-to-a-function-component)
44+
* [Как я могу измерить узел DOM?](#how-can-i-measure-a-dom-node)
4545
* [Что значит `const [thing, setThing] = useState()`?](#what-does-const-thing-setthing--usestate-mean)
4646
* [Оптимизации производительности](#performance-optimizations)
4747
* [Могу ли я пропустить эффект при обновлениях?](#can-i-skip-an-effect-on-updates)
@@ -62,52 +62,6 @@ prev: hooks-reference.html
6262
### В какой версии React появились хуки? {#which-versions-of-react-include-hooks}
6363

6464
Начиная с релиза 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)
91-
* **[Performance Optimizations](#performance-optimizations)**
92-
* [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
11165

11266
* React DOM
11367
* React DOM Server
@@ -450,7 +404,7 @@ function Example() {
450404

451405
Если вы намеренно хотите считать из асинхронного колбэка *свежайшее* состояние, вы можете сперва сохранить его [в реф](/docs/hooks-faq.html#is-there-something-like-instance-variables), потом изменить его и затем считать его из рефа.
452406

453-
Наконец, возможна другая ситуация, почему вы видите устаревшие пропсы или состояние: когда вы используете оптимизацию с помощью «массива зависимостей», но неправильно указали какие-то зависимости. Например, если эффект передаёт вторым параметром `[]`, но при этом использует `someProp`, то он продолжит «видеть» исходное значение `someProp`. Правильным решением является либо исправление массива, либо отказ от его использования.
407+
Наконец, возможна другая ситуация, почему вы видите устаревшие пропсы или состояние: когда вы используете оптимизацию с помощью «массива зависимостей», но неправильно указали какие-то зависимости. Например, если эффект передаёт вторым параметром `[]`, но при этом использует `someProp`, то он продолжит «видеть» исходное значение `someProp`. Правильным решением является либо исправление массива, либо отказ от его использования.
454408
По этим ссылкам описаны [подходы к функциям](#is-it-safe-to-omit-functions-from-the-list-of-dependencies) в аналогичных ситуациях и [другие известные способы](#what-can-i-do-if-my-effect-dependencies-change-too-often) снижения частоты вызова эффектов, исключающие передачу неправильных зависимостей.
455409

456410
>Примечание
@@ -498,15 +452,11 @@ function ScrollView({row}) {
498452

499453
### Могу ли я изменить реф, переданный в функциональный компонент? {#can-i-make-a-ref-to-a-function-component}
500454

501-
502455
Несмотря на то, что вам не понадобится это часто, вы можете предоставить некоторые императивные методы родительскому компоненту, используя хук [`useImperativeHandle`](/docs/hooks-reference.html#useimperativehandle).
503456

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}
508458

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):
510460

511461
```js{4-8,12}
512462
function MeasureExample() {
@@ -520,18 +470,18 @@ function MeasureExample() {
520470
521471
return (
522472
<>
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>
525475
</>
526476
);
527477
}
528478
```
529479

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) (например, в ответ на клик), мы по-прежнему получаем уведомление об этом в родительском компоненте и можем обновлять измерения.
531481

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 не вызовет его без необходимости.
533483

534-
If you want, you can [extract this logic](https://codesandbox.io/s/m5o42082xy) into a reusable Hook:
484+
При желании вы можете [извлечь эту логику](https://codesandbox.io/s/m5o42082xy) в многоразовый хук:
535485

536486
```js{2}
537487
function MeasureExample() {
@@ -558,8 +508,7 @@ function useClientRect() {
558508
```
559509

560510

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}
563512

564513
Если вы не знакомы с этим синтаксисом, ознакомьтесь с [объяснением](/docs/hooks-state.html#tip-what-do-square-brackets-mean) в документации хука состояния.
565514

@@ -962,13 +911,8 @@ function Form() {
962911
const [text, updateText] = useState('');
963912
const textRef = useRef();
964913
965-
<<<<<<< HEAD
966-
useLayoutEffect(() => {
967-
textRef.current = text; // Записать в реф
968-
=======
969914
useEffect(() => {
970-
textRef.current = text; // Write it to the ref
971-
>>>>>>> 1f2dbb7a4f531d1c9d70ae69e025eac992b37c6a
915+
textRef.current = text; // Записать это в реф
972916
});
973917
974918
const handleSubmit = useCallback(() => {

0 commit comments

Comments
 (0)