From efe2029f585f4e9f6853f604a3fd884ed6224e17 Mon Sep 17 00:00:00 2001 From: Egor Zekov Date: Fri, 1 Mar 2019 11:27:22 +0300 Subject: [PATCH 001/104] Hooks FAQ translation (WIP) --- content/docs/hooks-faq.md | 148 ++++++++++++++++++++------------------ 1 file changed, 79 insertions(+), 69 deletions(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index b3b99de90..9f9c7eab2 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -1,13 +1,13 @@ --- id: hooks-faq -title: Hooks FAQ +title: Хуки - вопросы и ответы permalink: docs/hooks-faq.html prev: hooks-reference.html --- -*Hooks* are a new addition in React 16.8. They let you use state and other React features without writing a class. +*Хуки* были добавлены в React 16.8. С их помощью вы можете использовать состояние и другие возможность React без необходимости использовать классы. -This page answers some of the frequently asked questions about [Hooks](/docs/hooks-overview.html). +На этой странице вы найдёте ответы на некоторые популярные вопросы о [Хуках](/docs/hooks-overview.html). -* **[Adoption Strategy](#adoption-strategy)** - * [Which versions of React include Hooks?](#which-versions-of-react-include-hooks) - * [Do I need to rewrite all my class components?](#do-i-need-to-rewrite-all-my-class-components) - * [What can I do with Hooks that I couldn't with classes?](#what-can-i-do-with-hooks-that-i-couldnt-with-classes) - * [How much of my React knowledge stays relevant?](#how-much-of-my-react-knowledge-stays-relevant) - * [Should I use Hooks, classes, or a mix of both?](#should-i-use-hooks-classes-or-a-mix-of-both) - * [Do Hooks cover all use cases for classes?](#do-hooks-cover-all-use-cases-for-classes) - * [Do Hooks replace render props and higher-order components?](#do-hooks-replace-render-props-and-higher-order-components) - * [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) - * [Do Hooks work with static typing?](#do-hooks-work-with-static-typing) - * [How to test components that use Hooks?](#how-to-test-components-that-use-hooks) - * [What exactly do the lint rules enforce?](#what-exactly-do-the-lint-rules-enforce) -* **[From Classes to Hooks](#from-classes-to-hooks)** - * [How do lifecycle methods correspond to Hooks?](#how-do-lifecycle-methods-correspond-to-hooks) +* **[Внедрение хуков](#adoption-strategy)** + * [В какой версии React появились хуки?](#which-versions-of-react-include-hooks) + * [Надо ли переписать все мои классовые компоненты?](#do-i-need-to-rewrite-all-my-class-components) + * [Что я могу сделать с помощью Хуков, что не смог бы с помощью классов?](#what-can-i-do-with-hooks-that-i-couldnt-with-classes) + * [Какая часть моих знаний о React всё еще актуальна?](#how-much-of-my-react-knowledge-stays-relevant) + * [Что мне использовать: Хуки, классы или оба подхода?](#should-i-use-hooks-classes-or-a-mix-of-both) + * [Дают ли Хуки все возможности классов?](#do-hooks-cover-all-use-cases-for-classes) + * [Являются ли Хуки заменой рендер-пропсам и компонентам высшего порядка?](#do-hooks-replace-render-props-and-higher-order-components) + * [Как Хуки повлияют на популярные API - например Redux `connect()` и React Router?](#what-do-hooks-mean-for-popular-apis-like-redux-connect-and-react-router) + * [Хуки поддерживают статическую типизацию?](#do-hooks-work-with-static-typing) + * [Как тестировать компоненты, которые используют Хуки?](#how-to-test-components-that-use-hooks) + * [Что конкретно правила линтера проверяют в Хуках?](#what-exactly-do-the-lint-rules-enforce) +* **[От классов к Хукам](#from-classes-to-hooks)** + * [Как методы жизненного цикла соответствуют Хукам?](#how-do-lifecycle-methods-correspond-to-hooks) * [Is there something like instance variables?](#is-there-something-like-instance-variables) * [Should I use one or many state variables?](#should-i-use-one-or-many-state-variables) * [Can I run an effect only on updates?](#can-i-run-an-effect-only-on-updates) @@ -52,87 +52,95 @@ This page answers some of the frequently asked questions about [Hooks](/docs/hoo * [How does React associate Hook calls with components?](#how-does-react-associate-hook-calls-with-components) * [What is the prior art for Hooks?](#what-is-the-prior-art-for-hooks) -## Adoption Strategy {#adoption-strategy} +## Внедрение хуков {#adoption-strategy} -### Which versions of React include Hooks? {#which-versions-of-react-include-hooks} +### В какой версии React появились хуки?{#which-versions-of-react-include-hooks} -Starting with 16.8.0, React includes a stable implementation of React Hooks for: +Начиная с релиза 16.8.0, React включает в себя стабильную реализацию Хуков для: * React DOM * React DOM Server * React Test Renderer * React Shallow Renderer -Note that **to enable Hooks, all React packages need to be 16.8.0 or higher**. Hooks won't work if you forget to update, for example, React DOM. +Обратите внимание, **чтобы Хуки стали доступны, все React-пакеты должны быть версии 16.8.0 или выше**. Хуки не будут работать, если вы, например, забудете обновить React DOM. -React Native will fully support Hooks in its next stable release. +Поддержка Хуков в React Native добавится в следующем стабильном релизе. -### Do I need to rewrite all my class components? {#do-i-need-to-rewrite-all-my-class-components} +### Надо ли переписать все мои классовые компоненты?{#do-i-need-to-rewrite-all-my-class-components} No. There are [no plans](/docs/hooks-intro.html#gradual-adoption-strategy) to remove classes from React -- we all need to keep shipping products and can't afford rewrites. We recommend trying Hooks in new code. -### What can I do with Hooks that I couldn't with classes? {#what-can-i-do-with-hooks-that-i-couldnt-with-classes} +Нет. [Планов по удалению классов из React нет](/docs/hooks-intro.html#gradual-adoption-strategy) -- нам всем необходимо добавлять новую функциональность, вместо переписывания всего приложения. Мы рекомендуем пробовать Хуки в новом коде. -Hooks offer a powerful and expressive new way to reuse functionality between components. ["Building Your Own Hooks"](/docs/hooks-custom.html) provides a glimpse of what's possible. [This article](https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889) by a React core team member dives deeper into the new capabilities unlocked by Hooks. +### Что я могу сделать с помощью Хуков, что не смог бы с помощью классов? {#what-can-i-do-with-hooks-that-i-couldnt-with-classes} -### How much of my React knowledge stays relevant? {#how-much-of-my-react-knowledge-stays-relevant} +Хуки дают отличный способ повторного использования кода между компонентами. ["Создание ваших Хуков"](/docs/hooks-custom.html) показывает, что вы сможете сделать. [Эта статья](https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889), написанная одим из главных участников React-команды, описывает новые возможности, разблокированные релизом Хуков. -Hooks are a more direct way to use the React features you already know -- such as state, lifecycle, context, and refs. They don't fundamentally change how React works, and your knowledge of components, props, and top-down data flow is just as relevant. +### Какая часть моих знаний о React всё еще актуальна? {#how-much-of-my-react-knowledge-stays-relevant} -Hooks do have a learning curve of their own. If there's something missing in this documentation, [raise an issue](https://github.com/reactjs/reactjs.org/issues/new) and we'll try to help. +Хуки -- это новый способ использование возможностей React, которые вы уже знаете, таких, как состояние, жизненный цикл, контекст и рефы. Хуки не изменили фундаментальную логику React, и ваши знания компонентов, пропсов и потока данных сверху-вниз остаются актуальными. -### Should I use Hooks, classes, or a mix of both? {#should-i-use-hooks-classes-or-a-mix-of-both} +Однако, Хуки -- это не самая простая часть React. Если вам не хватает чего-то в этой документации, [дайте нам знать](https://github.com/reactjs/reactjs.org/issues/new), и мы постараемся вам помочь. -When you're ready, we'd encourage you to start trying Hooks in new components you write. Make sure everyone on your team is on board with using them and familiar with this documentation. We don't recommend rewriting your existing classes to Hooks unless you planned to rewrite them anyway (e.g. to fix bugs). +### Что мне использовать: Хуки, классы или оба подхода? {#should-i-use-hooks-classes-or-a-mix-of-both} -You can't use Hooks *inside* of a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components. +Когда вы будете готовы, мы бы очень хотели, чтобы вы начали использовать Хуки в ваших новых компонентах. Убедитесь, чтобы ваши коллеги ознакомились с документацией и поддержали вас. Мы не рекомендуем сразу перепесивать ваши существующие классы на Хуки, пока вы сами не запланируете переписать их (например, чтобы исправить баг). -### Do Hooks cover all use cases for classes? {#do-hooks-cover-all-use-cases-for-classes} +Вы не можете использовать Хуки *внутри* классового компонента, но вы можете комбинировать классы и функциональные компоненты с Хуками в одном дереве. Классовый компонент или функциональный с Хуками - неважно, это всего-лишь особенности реализации. В дальнейшем будущем, мы ожидаем, что Хуки статун главным способ написания React-компонентов. -Our goal is for Hooks to cover all use cases for classes as soon as possible. There are no Hook equivalents to the uncommon `getSnapshotBeforeUpdate` and `componentDidCatch` lifecycles yet, but we plan to add them soon. +### Дают ли Хуки все возможности классов? {#do-hooks-cover-all-use-cases-for-classes} -It is an early time for Hooks, and some third-party libraries might not be compatible with Hooks at the moment. +Наша задача для Хуков - это полное покрытие функционала классов чем раньше, тем лучше. Пока не существует Хуков, реализующих методы жизненного цикла `getSnapshotBeforeUpdate` и `componentDidCatch`, но мы планируем скоро их добавить. -### Do Hooks replace render props and higher-order components? {#do-hooks-replace-render-props-and-higher-order-components} +Хуки появились совсем недавно, и некоторые сторонние библиотеки могли еще не приспособиться к ним. + +### Являются ли Хуки заменой рендер-пропсам и компонентам высшего порядка? {#do-hooks-replace-render-props-and-higher-order-components} Often, render props and higher-order components render only a single child. We think Hooks are a simpler way to serve this use case. There is still a place for both patterns (for example, a virtual scroller component might have a `renderItem` prop, or a visual container component might have its own DOM structure). But in most cases, Hooks will be sufficient and can help reduce nesting in your tree. -### 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} +Обычно, рендер пропсы и компоненты высшего порядка рендерят только один дочерний компонент. Мы думаем, что Хуки - более простой способ сделать это. +TODO +Но в большинстве случаев, Хуки должны помочь уменьшить вложенность компонентов в вашем дереве. + +### Как Хуки повлияют на популярные API - например Redux `connect()` и React Router? {#what-do-hooks-mean-for-popular-apis-like-redux-connect-and-react-router}. -You can continue to use the exact same APIs as you always have; they'll continue to work. +Вы можете продолжать использовать тот же API, который вы использовали до этого - всё продолжает работать. -In the future, new versions of these libraries might also export custom Hooks such as `useRedux()` or `useRouter()` that let you use the same features without needing wrapper components. +В будущем, новые версии этих библиотек могут также экспортировать специальные Хуки, например `useRedux()` или `useRouter()`, которые позволят вам использовать тот же функционал без необходимости обарачивать компоненты. -### Do Hooks work with static typing? {#do-hooks-work-with-static-typing} +### Хуки поддерживают статическую типизацию? {#do-hooks-work-with-static-typing} -Hooks were designed with static typing in mind. Because they're functions, they are easier to type correctly than patterns like higher-order components. The latest Flow and TypeScript React definitions include support for React Hooks. +Хуки спроектированы с учётом статической типизации. Так как они являются функциями, их легче типизировать правильно чем, например, компоненты высшего порядка. Последние версии Flow и TypeScript включают в себя поддержку React-хуков. Importantly, custom Hooks give you the power to constrain React API if you'd like to type them more strictly in some way. React gives you the primitives, but you can combine them in different ways than what we provide out of the box. -### How to test components that use Hooks? {#how-to-test-components-that-use-hooks} +TODO -From React's point of view, a component using Hooks is just a regular component. If your testing solution doesn't rely on React internals, testing components with Hooks shouldn't be different from how you normally test components. +### Как тестировать компоненты, которые используют Хуки? {#how-to-test-components-that-use-hooks} -For example, let's say we have this counter component: +С точки зрения React, компонент, использующий Хуки, является обычным компонентом. Если ваш способ тестирования не опирается на внутреннюю часть React, тестирование компонентов с Хуками не должно отличатся от тестирования других компонентов. + +Например, у нас есть этот компонент-счетчик: ```js function Example() { const [count, setCount] = useState(0); useEffect(() => { - document.title = `You clicked ${count} times`; + document.title = `Вы нажали ${count} раз`; }); return (
-

You clicked {count} times

+

Вы нажали {count} раз

); } ``` -We'll test it using React DOM. To make sure that the behavior matches what happens in the browser, we'll wrap the code rendering and updating it into [`ReactTestUtils.act()`](/docs/test-utils.html#act) calls: +Мы будем тестировать этот компонент с помощью React DOM. Чтобы убедиться, что поведение совпадает с тем, что случится в браузере, мы обернём код рендера и обновления в вызов [`ReactTestUtils.act()`](/docs/test-utils.html#act): ```js{3,20-22,29-31} import React from 'react'; @@ -153,56 +161,58 @@ afterEach(() => { }); it('can render and update a counter', () => { - // Test first render and effect + // Тестируем первый рендер и эффект act(() => { ReactDOM.render(, container); }); const button = container.querySelector('button'); const label = container.querySelector('p'); - expect(label.textContent).toBe('You clicked 0 times'); - expect(document.title).toBe('You clicked 0 times'); + expect(label.textContent).toBe('Вы нажали 0 раз'); + expect(document.title).toBe('Вы нажали 0 раз'); - // Test second render and effect + // Тестируем второй рендер и эффект act(() => { button.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); - expect(label.textContent).toBe('You clicked 1 times'); - expect(document.title).toBe('You clicked 1 times'); + expect(label.textContent).toBe('Вы нажали 1 раз'); + expect(document.title).toBe('Вы нажали 1 раз'); }); ``` -The calls to `act()` will also flush the effects inside of them. +Вызовы `act()` также запустят эффекты внутри. -If you need to test a custom Hook, you can do so by creating a component in your test, and using your Hook from it. Then you can test the component you wrote. +Если вам надо протестировать созданный Хук, вы можете создать компонент в ваших тестах и использовать в нём этот Хук. После этого вы можете протестировать сам компонент. -To reduce the boilerplate, we recommend using [`react-testing-library`](https://git.io/react-testing-library) which is designed to encourage writing tests that use your components as the end users do. +Для уменьшения однотипного кода, мы советуем использовать библиотеку [`react-testing-library`](https://git.io/react-testing-library). Она была создана для написания тестов, использующих ваши компоненты, как это делают конечные пользователи. -### What exactly do the [lint rules](https://www.npmjs.com/package/eslint-plugin-react-hooks) enforce? {#what-exactly-do-the-lint-rules-enforce} +### Что конкретно [правила линтера](https://www.npmjs.com/package/eslint-plugin-react-hooks) проверяют в Хуках?{#what-exactly-do-the-lint-rules-enforce} -We provide an [ESLint plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) that enforces [rules of Hooks](/docs/hooks-rules.html) to avoid bugs. It assumes that any function starting with "`use`" and a capital letter right after it is a Hook. We recognize this heuristic isn't perfect and there may be some false positives, but without an ecosystem-wide convention there is just no way to make Hooks work well -- and longer names will discourage people from either adopting Hooks or following the convention. +Мы предоставляем [плагин к ESLint](https://www.npmjs.com/package/eslint-plugin-react-hooks), который принуждает следовать [правилам Хуков](/docs/hooks-rules.html), чтобы избежать ошибок. Подразумевается, что любая функция, имя который начинается с "`use`" и заглавной буквы далее, является Хуком. Мы понимаем, что это предположение не идеальное, и могут случится ложные срабатывания. Однако, без этого важного соглашения, было бы невозможно заставить Хуки работать хорошо, а более длинные имена могли бы помешать людям начать использовать Хуки или следовать соглашению. -In particular, the rule enforces that: +В частности, правила проверяют, что: -* Calls to Hooks are either inside a `PascalCase` function (assumed to be a component) or another `useSomething` function (assumed to be a custom Hook). -* Hooks are called in the same order on every render. +* Вызовы Хуков происходят либо внутри функции с именем в `ВерблюжемРегистре` (подразумевается, что это класс), либо внутри другой `useSomething` функции (подразумевается, что это созданный пользователем Хук). +* Хуки вызываются в одном и том же порядке каждый раз. -There are a few more heuristics, and they might change over time as we fine-tune the rule to balance finding bugs with avoiding false positives. +Существует еще несколько предположений, которые могут измениться по мере того, как мы будем регулировать правила и искать баланс между нахождением ошибок и ложными срабатываниями. -## From Classes to Hooks {#from-classes-to-hooks} +## От классов к Хукам {#from-classes-to-hooks} -### How do lifecycle methods correspond to Hooks? {#how-do-lifecycle-methods-correspond-to-hooks} +### [Как методы жизненного цикла соответствуют Хукам?] {#how-do-lifecycle-methods-correspond-to-hooks} -* `constructor`: Function components don't need a constructor. You can initialize the state in the [`useState`](/docs/hooks-reference.html#usestate) call. If computing the initial state is expensive, you can pass a function to `useState`. +* `constructor`: Функциональному компоненту не нужен конструктор. Вы можете инициализировать состояние, используя вызов [`useState`](/docs/hooks-reference.html#usestate). Если вычисления состояния трудозатратны, вы можете передать функцию в `useState`. * `getDerivedStateFromProps`: Schedule an update [while rendering](#how-do-i-implement-getderivedstatefromprops) instead. -* `shouldComponentUpdate`: See `React.memo` [below](#how-do-i-implement-shouldcomponentupdate). +* `getDerivedStateFromProps`: TODO + +* `shouldComponentUpdate`: Смотрите `React.memo` [below](#how-do-i-implement-shouldcomponentupdate). -* `render`: This is the function component body itself. +* `render`: Это тело функционального компонента. -* `componentDidMount`, `componentDidUpdate`, `componentWillUnmount`: The [`useEffect` Hook](/docs/hooks-reference.html#useeffect) can express all combinations of these (including [less](#can-i-skip-an-effect-on-updates) [common](#can-i-run-an-effect-only-on-updates) cases). +* `componentDidMount`, `componentDidUpdate`, `componentWillUnmount`: [`useEffect` Хук](/docs/hooks-reference.html#useeffect) заменяет все их комбинации (включая [более](#can-i-skip-an-effect-on-updates) [редкие](#can-i-run-an-effect-only-on-updates) случаи). -* `componentDidCatch` and `getDerivedStateFromError`: There are no Hook equivalents for these methods yet, but they will be added soon. +* `componentDidCatch` и `getDerivedStateFromError`: В данный момент не существует Хуков-аналогов для этих методов, но они будут скоро добавлены. ### Is there something like instance variables? {#is-there-something-like-instance-variables} From 45141d74590c4bc48599ca0cb1f9cec146858555 Mon Sep 17 00:00:00 2001 From: Egor Zekov Date: Sun, 3 Mar 2019 14:00:42 +0300 Subject: [PATCH 002/104] More sections translated --- content/docs/hooks-faq.md | 60 +++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index 9f9c7eab2..559bfadee 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -32,10 +32,10 @@ prev: hooks-reference.html * [Что конкретно правила линтера проверяют в Хуках?](#what-exactly-do-the-lint-rules-enforce) * **[От классов к Хукам](#from-classes-to-hooks)** * [Как методы жизненного цикла соответствуют Хукам?](#how-do-lifecycle-methods-correspond-to-hooks) - * [Is there something like instance variables?](#is-there-something-like-instance-variables) - * [Should I use one or many state variables?](#should-i-use-one-or-many-state-variables) - * [Can I run an effect only on updates?](#can-i-run-an-effect-only-on-updates) - * [How to get the previous props or state?](#how-to-get-the-previous-props-or-state) + * [Существует что-нибудь наподобие полей экземпляра?](#is-there-something-like-instance-variables) + * [Сколько переменных состояния я могу использовать - одну или несколько?](#should-i-use-one-or-many-state-variables) + * [Могу ли я использовать эфеект только на обновлениях компонента?](#can-i-run-an-effect-only-on-updates) + * [Как получить прошлые пропсы или состояние](#how-to-get-the-previous-props-or-state) * [How do I implement getDerivedStateFromProps?](#how-do-i-implement-getderivedstatefromprops) * [Is there something like forceUpdate?](#is-there-something-like-forceupdate) * [Can I make a ref to a function component?](#can-i-make-a-ref-to-a-function-component) @@ -214,11 +214,11 @@ it('can render and update a counter', () => { * `componentDidCatch` и `getDerivedStateFromError`: В данный момент не существует Хуков-аналогов для этих методов, но они будут скоро добавлены. -### Is there something like instance variables? {#is-there-something-like-instance-variables} +### Существует что-нибудь наподобие полей экземпляра? {#is-there-something-like-instance-variables} -Yes! The [`useRef()`](/docs/hooks-reference.html#useref) Hook isn't just for DOM refs. The "ref" object is a generic container whose `current` property is mutable and can hold any value, similar to an instance property on a class. +Да! Хук [`useRef()`](/docs/hooks-reference.html#useref) может использоваться не только для DOM рефов. Реф - это общий контейнер, а его поле `current` -- изменяемое и может хранить любое значение, как и поле экземпляра класса. -You can write to it from inside `useEffect`: +Вы можете использовать его внутри `useEffect`: ```js{2,8} function Timer() { @@ -238,7 +238,7 @@ function Timer() { } ``` -If we just wanted to set an interval, we wouldn't need the ref (`id` could be local to the effect), but it's useful if we want to clear the interval from an event handler: +Если мы захотим просто установить интервал, нам не нужен будет реф (`id` может использоваться только внутри эффекта). Но реф будет полезным, если мы захотим очистить интервал из обработчика события: ```js{3} // ... @@ -248,11 +248,11 @@ If we just wanted to set an interval, we wouldn't need the ref (`id` could be lo // ... ``` -Conceptually, you can think of refs as similar to instance variables in a class. Unless you're doing [lazy initialization](#how-to-create-expensive-objects-lazily), avoid setting refs during rendering -- this can lead to surprising behavior. Instead, typically you want to modify refs in event handlers and effects. +В целом вы можете рассматривать рефы как поля экземпляра класса. Старайтесь избегать установки рефов во время рендера, пока вы не занимаетесь [ленивой инициализацией](#how-to-create-expensive-objects-lazily), так как это может привести к неожиданному поведению. Вместо этого, зачастую вы будете изменять рефы в обработчиках событий и эффектах. -### Should I use one or many state variables? {#should-i-use-one-or-many-state-variables} +### Сколько переменных состояния я могу использовать - одну или несколько? {#should-i-use-one-or-many-state-variables} -If you're coming from classes, you might be tempted to always call `useState()` once and put all state into a single object. You can do it if you'd like. Here is an example of a component that follows the mouse movement. We keep its position and size in the local state: +Если вы привыкли писать классовые компоненты, вы скорее всего всегда вызываете `useState()` один раз для одного изменения состояния и храните всё состояние в одном объекте. Вы можете делать то же самое с хуками, если пожелаете. Взгляните на пример компонента, который следует за движением курсора. Мы храним позицию и размер этого компонента в локальном состоянии. ```js function Box() { @@ -261,27 +261,27 @@ function Box() { } ``` -Now let's say we want to write some logic that changes `left` and `top` when the user moves their mouse. Note how we have to merge these fields into the previous state object manually: +Допустим, мы хотим написать некоторую логику, которая будет изменять значения `left` и `top`, когда пользователь двигает курсор мышки. Обратите внимание, что мы обязаны объединять эти поля с предыдущим объектом состоянии вручную: ```js{4,5} // ... useEffect(() => { function handleWindowMouseMove(e) { - // Spreading "...state" ensures we don't "lose" width and height + // Использование "...state" гарантирует, что мы не `потеряем` поля width и height setState(state => ({ ...state, left: e.pageX, top: e.pageY })); } - // Note: this implementation is a bit simplified + // Примичание: эта реализация немного упрощена window.addEventListener('mousemove', handleWindowMouseMove); return () => window.removeEventListener('mousemove', handleWindowMouseMove); }, []); // ... ``` -This is because when we update a state variable, we *replace* its value. This is different from `this.setState` in a class, which *merges* the updated fields into the object. +Это необходимо, потому что мы изменяем переменную состояния, *заменяя* её значение. Данное поведение отличается от `this.setState`, ведь этот классовый метод *объединяет* изменённые поля и текущий объект состояния. -If you miss automatic merging, you can write a custom `useLegacyState` Hook that merges object state updates. However, instead **we recommend to split state into multiple state variables based on which values tend to change together.** +Если вам не хватает автоматического объединения состояния, вы можете например свой хук `useLegacyState`, который будет объединять обновленные поля. Однако, вместо этого **мы рекомендуем разделять состояние на несколько переменных, учитывая какие поля логически относятся друг к другу и будут изменяться вместе.** -For example, we could split our component state into `position` and `size` objects, and always replace the `position` with no need for merging: +Например, мы можем разделить состояние нашего компонента на объекты `position` и `size`, что поможет всегда изменять только `position`, без необходимости волноваться об объединении: ```js{2,7} function Box() { @@ -295,7 +295,7 @@ function Box() { // ... ``` -Separating independent state variables also has another benefit. It makes it easy to later extract some related logic into a custom Hook, for example: +В разделении состояния на независимые переменные есть еще одно преимущество. Это поможет легко вынести некоторую логику в отдельный хук в будущем, например: ```js{2,7} function Box() { @@ -313,17 +313,17 @@ function useWindowPosition() { } ``` -Note how we were able to move the `useState` call for the `position` state variable and the related effect into a custom Hook without changing their code. If all state was in a single object, extracting it would be more difficult. +Обратите внимание, как мы смогли вынести вызов `useState`, изменящий `position`, и соответствующих эффект в отдельный хук, практически не меняя их код. Если бы всё состояние хранилось в одном объекте, сделать это перемещение было бы на порядок сложнее. -Both putting all state in a single `useState` call, and having a `useState` call per each field can work. Components tend to be most readable when you find a balance between these two extremes, and group related state into a few independent state variables. If the state logic becomes complex, we recommend [managing it with a reducer](/docs/hooks-reference.html#usereducer) or a custom Hook. +Оба варинта работают на самом деле работают. Компоненты будут более читаемыми, если вы найдёте баланс между двумя подходами и будете групировать связанные друг с другом данные. Если работа с состоянием становится сложной, мы советуем [использовать редюсер](/docs/hooks-reference.html#usereducer) или выносить логику в отдельные хуки. -### Can I run an effect only on updates? {#can-i-run-an-effect-only-on-updates} +### Могу ли я использовать эфеект только на обновлениях компонента? {#can-i-run-an-effect-only-on-updates} -This is a rare use case. If you need it, you can [use a mutable ref](#is-there-something-like-instance-variables) to manually store a boolean value corresponding to whether you are on the first or a subsequent render, then check that flag in your effect. (If you find yourself doing this often, you could create a custom Hook for it.) +Это - довольно редкий случай. Вы можете [использовать изменяемый реф](#is-there-something-like-instance-variables), чтобы вручную хранить логическое значение, показывающее, прошел ли первый рендер. В свою очередь эффект может опираться на это значение. Если вы замечаете, что эта логика нужна вам часто, вы можете вынести её в отдельный хук. -### How to get the previous props or state? {#how-to-get-the-previous-props-or-state} +### Как получить прошлые пропсы или состояние? {#how-to-get-the-previous-props-or-state} -Currently, you can do it manually [with a ref](#is-there-something-like-instance-variables): +Сейчас, вы можете сделать это вручную, [используя реф](#is-there-something-like-instance-variables): ```js{6,8} function Counter() { @@ -335,17 +335,17 @@ function Counter() { }); const prevCount = prevCountRef.current; - return

Now: {count}, before: {prevCount}

; + return

Сейчас: {count}, до этого: {prevCount}

; } ``` -This might be a bit convoluted but you can extract it into a custom Hook: +Это может показаться чрезмерно сложным, но вы можете вынести эту логику в отдельный хук: ```js{3,7} function Counter() { const [count, setCount] = useState(0); const prevCount = usePrevious(count); - return

Now: {count}, before: {prevCount}

; + return

Сейчас: {count}, до этого: {prevCount}

; } function usePrevious(value) { @@ -357,7 +357,7 @@ function usePrevious(value) { } ``` -Note how this would work for props, state, or any other calculated value. +Обратите внимание, как это будет работать для пропсов, состояния или любого другого вычисляемого значения. ```js{5} function Counter() { @@ -368,9 +368,9 @@ function Counter() { // ... ``` -It's possible that in the future React will provide a `usePrevious` Hook out of the box since it's a relatively common use case. +Возмонжо, в будущем React добавит хук `usePrevious` в свой API, так как это довольно распространенный случай в разработке. -See also [the recommended pattern for derived state](#how-do-i-implement-getderivedstatefromprops). +Также смотрите [рекомендованный паттерн для полученного состояния](#how-do-i-implement-getderivedstatefromprops). ### How do I implement `getDerivedStateFromProps`? {#how-do-i-implement-getderivedstatefromprops} From f3470f571610ec9a7cefbfcf97519a93a1673066 Mon Sep 17 00:00:00 2001 From: Anton Ahatov Date: Sun, 3 Mar 2019 14:04:44 +0300 Subject: [PATCH 003/104] Update content/docs/hooks-faq.md Co-Authored-By: egorzekov --- content/docs/hooks-faq.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index 559bfadee..3afeb4bc5 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -81,7 +81,7 @@ No. There are [no plans](/docs/hooks-intro.html#gradual-adoption-strategy) to re Хуки -- это новый способ использование возможностей React, которые вы уже знаете, таких, как состояние, жизненный цикл, контекст и рефы. Хуки не изменили фундаментальную логику React, и ваши знания компонентов, пропсов и потока данных сверху-вниз остаются актуальными. -Однако, Хуки -- это не самая простая часть React. Если вам не хватает чего-то в этой документации, [дайте нам знать](https://github.com/reactjs/reactjs.org/issues/new), и мы постараемся вам помочь. +Однако, хуки не самая простая часть React. Если вам чего-то не хватает в этой документации, [дайте нам знать](https://github.com/reactjs/reactjs.org/issues/new), и мы постараемся вам помочь. ### Что мне использовать: Хуки, классы или оба подхода? {#should-i-use-hooks-classes-or-a-mix-of-both} From 6353a9e0a01a16839e4d141201b0e5746aecd418 Mon Sep 17 00:00:00 2001 From: Anton Ahatov Date: Sun, 3 Mar 2019 14:05:01 +0300 Subject: [PATCH 004/104] Update content/docs/hooks-faq.md Co-Authored-By: egorzekov --- content/docs/hooks-faq.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index 3afeb4bc5..8bd20d370 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -79,7 +79,7 @@ No. There are [no plans](/docs/hooks-intro.html#gradual-adoption-strategy) to re ### Какая часть моих знаний о React всё еще актуальна? {#how-much-of-my-react-knowledge-stays-relevant} -Хуки -- это новый способ использование возможностей React, которые вы уже знаете, таких, как состояние, жизненный цикл, контекст и рефы. Хуки не изменили фундаментальную логику React, и ваши знания компонентов, пропсов и потока данных сверху-вниз остаются актуальными. +Хуки -- это новый способ использовать возможности React, которые вы уже знаете: состояние, жизненный цикл, контекст и рефы. Хуки не изменили фундаментальную логику React, и ваши знания компонентов, пропсов и потока данных сверху-вниз остаются актуальными. Однако, хуки не самая простая часть React. Если вам чего-то не хватает в этой документации, [дайте нам знать](https://github.com/reactjs/reactjs.org/issues/new), и мы постараемся вам помочь. From ea2999f9d2323cefafdfd23c8098c21e43b62742 Mon Sep 17 00:00:00 2001 From: Anton Ahatov Date: Sun, 3 Mar 2019 14:05:44 +0300 Subject: [PATCH 005/104] Update content/docs/hooks-faq.md Co-Authored-By: egorzekov --- content/docs/hooks-faq.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index 8bd20d370..a0bd52fa7 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -75,7 +75,7 @@ No. There are [no plans](/docs/hooks-intro.html#gradual-adoption-strategy) to re ### Что я могу сделать с помощью Хуков, что не смог бы с помощью классов? {#what-can-i-do-with-hooks-that-i-couldnt-with-classes} -Хуки дают отличный способ повторного использования кода между компонентами. ["Создание ваших Хуков"](/docs/hooks-custom.html) показывает, что вы сможете сделать. [Эта статья](https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889), написанная одим из главных участников React-команды, описывает новые возможности, разблокированные релизом Хуков. +Хуки дают новый мощный способ переиспользования кода между компонентами. ["Создание ваших хуков"](/docs/hooks-custom.html) даст представление об их возможностях. [Эта статья](https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889), написанная одним из участников команды React, описывает новые возможности, которые открывают хуки. ### Какая часть моих знаний о React всё еще актуальна? {#how-much-of-my-react-knowledge-stays-relevant} From 8ca661fca395cb37d8b6f4e83ab06b603122735e Mon Sep 17 00:00:00 2001 From: Anton Ahatov Date: Sun, 3 Mar 2019 14:06:09 +0300 Subject: [PATCH 006/104] Update content/docs/hooks-faq.md Co-Authored-By: egorzekov --- content/docs/hooks-faq.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index a0bd52fa7..44a484175 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -71,7 +71,7 @@ prev: hooks-reference.html No. There are [no plans](/docs/hooks-intro.html#gradual-adoption-strategy) to remove classes from React -- we all need to keep shipping products and can't afford rewrites. We recommend trying Hooks in new code. -Нет. [Планов по удалению классов из React нет](/docs/hooks-intro.html#gradual-adoption-strategy) -- нам всем необходимо добавлять новую функциональность, вместо переписывания всего приложения. Мы рекомендуем пробовать Хуки в новом коде. +Нет. [Мы не собираемся удалять классы из React](/docs/hooks-intro.html#gradual-adoption-strategy). Это новая функциональность, которая не заставляет переписывать всё приложение. Мы рекомендуем пробовать Хуки только в новом коде. ### Что я могу сделать с помощью Хуков, что не смог бы с помощью классов? {#what-can-i-do-with-hooks-that-i-couldnt-with-classes} From a2ea8223c59fa9ee704c6ba211a7138c1022ba65 Mon Sep 17 00:00:00 2001 From: Anton Ahatov Date: Sun, 3 Mar 2019 14:06:26 +0300 Subject: [PATCH 007/104] Update content/docs/hooks-faq.md Co-Authored-By: egorzekov --- content/docs/hooks-faq.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index 44a484175..43b7b3820 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -63,7 +63,7 @@ prev: hooks-reference.html * React Test Renderer * React Shallow Renderer -Обратите внимание, **чтобы Хуки стали доступны, все React-пакеты должны быть версии 16.8.0 или выше**. Хуки не будут работать, если вы, например, забудете обновить React DOM. +Обратите внимание, что **хуки будут доступны, только если все React-пакеты версии 16.8.0 или выше**. Хуки не будут работать, если вы, например, забыли обновить React DOM. Поддержка Хуков в React Native добавится в следующем стабильном релизе. From f78c58b38ff5103594ae8d710f7e93e48e0af0f8 Mon Sep 17 00:00:00 2001 From: Anton Ahatov Date: Sun, 3 Mar 2019 14:06:47 +0300 Subject: [PATCH 008/104] Update content/docs/hooks-faq.md Co-Authored-By: egorzekov --- content/docs/hooks-faq.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index 43b7b3820..475598ad3 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -5,7 +5,7 @@ permalink: docs/hooks-faq.html prev: hooks-reference.html --- -*Хуки* были добавлены в React 16.8. С их помощью вы можете использовать состояние и другие возможность React без необходимости использовать классы. +*Хуки* были добавлены в React 16.8. С их помощью вы можете использовать состояние и другие возможности React без необходимости использовать классы. На этой странице вы найдёте ответы на некоторые популярные вопросы о [Хуках](/docs/hooks-overview.html). From 9ec576c7c06c73eb0b3376d06aa3818ed2cf67cf Mon Sep 17 00:00:00 2001 From: Anton Ahatov Date: Sun, 3 Mar 2019 14:07:08 +0300 Subject: [PATCH 009/104] Update content/docs/hooks-faq.md Co-Authored-By: egorzekov --- content/docs/hooks-faq.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index 475598ad3..b62ae937a 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -27,7 +27,7 @@ prev: hooks-reference.html * [Дают ли Хуки все возможности классов?](#do-hooks-cover-all-use-cases-for-classes) * [Являются ли Хуки заменой рендер-пропсам и компонентам высшего порядка?](#do-hooks-replace-render-props-and-higher-order-components) * [Как Хуки повлияют на популярные API - например Redux `connect()` и React Router?](#what-do-hooks-mean-for-popular-apis-like-redux-connect-and-react-router) - * [Хуки поддерживают статическую типизацию?](#do-hooks-work-with-static-typing) + * [Поддерживают ли хуки статическую типизацию?](#do-hooks-work-with-static-typing) * [Как тестировать компоненты, которые используют Хуки?](#how-to-test-components-that-use-hooks) * [Что конкретно правила линтера проверяют в Хуках?](#what-exactly-do-the-lint-rules-enforce) * **[От классов к Хукам](#from-classes-to-hooks)** From 9d9b0c7a5686752b4472df4b43d9015f859430f4 Mon Sep 17 00:00:00 2001 From: Egor Zekov Date: Sun, 3 Mar 2019 14:38:43 +0300 Subject: [PATCH 010/104] Fix hooks first letter --- content/docs/hooks-faq.md | 58 +++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index b62ae937a..24a210d70 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -7,7 +7,7 @@ prev: hooks-reference.html *Хуки* были добавлены в React 16.8. С их помощью вы можете использовать состояние и другие возможности React без необходимости использовать классы. -На этой странице вы найдёте ответы на некоторые популярные вопросы о [Хуках](/docs/hooks-overview.html). +На этой странице вы найдёте ответы на некоторые популярные вопросы о [хуках](/docs/hooks-overview.html).