diff --git a/content/docs/hooks-state.md b/content/docs/hooks-state.md index 052aecb33..272246d00 100644 --- a/content/docs/hooks-state.md +++ b/content/docs/hooks-state.md @@ -1,6 +1,6 @@ --- id: hooks-state -title: Using the State Hook +title: Использование хука состояния permalink: docs/hooks-state.html next: hooks-effect.html prev: hooks-overview.html @@ -8,31 +8,31 @@ prev: hooks-overview.html *Hooks* are a new addition in React 16.8. They let you use state and other React features without writing a class. -The [previous page](/docs/hooks-intro.html) introduced Hooks with this example: +На [предыдущей странице](/docs/hooks-intro.html) мы познакомились с хуками на этом примере: ```js{4-5} import React, { useState } from 'react'; function Example() { - // Declare a new state variable, which we'll call "count" + // Объявление новой переменной состояния «count» const [count, setCount] = useState(0); return (
-

You clicked {count} times

+

Вы кликнули {count} раз(а)

); } ``` -We'll start learning about Hooks by comparing this code to an equivalent class example. +Давайте начнём изучать хуки, сравнив этот код с эквивалентным кодом на основе класса. -## Equivalent Class Example {#equivalent-class-example} +## Эквивалентный пример с классом {#equivalent-class-example} -If you used classes in React before, this code should look familiar: +Если вы уже пользовались классами в React, то вам знаком такой код: ```js class Example extends React.Component { @@ -46,9 +46,9 @@ class Example extends React.Component { render() { return (
-

You clicked {this.state.count} times

+

Вы кликнули {this.state.count} раз(а)

); @@ -56,39 +56,39 @@ class Example extends React.Component { } ``` -The state starts as `{ count: 0 }`, and we increment `state.count` when the user clicks a button by calling `this.setState()`. We'll use snippets from this class throughout the page. +Сначала состояние выглядит как `{ count: 0 }`. Каждый раз, когда пользователь кликает, мы увеличиваем `state.count` на единицу, вызывая `this.setState()`. Мы будем использовать фрагменты этого класса на протяжении всей страницы. ->Note +>Примечание > ->You might be wondering why we're using a counter here instead of a more realistic example. This is to help us focus on the API while we're still making our first steps with Hooks. +>Возможно, вы спросите себя, почему мы используем в качестве примера счётчик, а не что-то более реалистичное. Дело в том, что мы хотим обратить ваше внимание на API, одновременно делая первые шаги с хуками. -## Hooks and Function Components {#hooks-and-function-components} +## Хуки и функциональные компоненты {#hooks-and-function-components} -As a reminder, function components in React look like this: +Напоминаем, что функциональные компоненты в React выглядят так: ```js const Example = (props) => { - // You can use Hooks here! + // Тут мог бы быть ваш хук! return
; } ``` -or this: +или так: ```js function Example(props) { - // You can use Hooks here! + // Тут мог бы быть ваш хук! return
; } ``` -You might have previously known these as "stateless components". We're now introducing the ability to use React state from these, so we prefer the name "function components". +Возможно, вы слышали, что такие компоненты называются «компонентами *без* состояния». Сейчас мы покажем, как использовать внутри них состояние React, поэтому будем называть их «функциональными компонентами». -Hooks **don't** work inside classes. But you can use them instead of writing classes. +Хуки **НЕ** работают внутри классов, а используются *вместо* них. -## What's a Hook? {#whats-a-hook} +## Что такое хук? {#whats-a-hook} -Our new example starts by importing the `useState` Hook from React: +Наш новый пример начинается с того, что импортирует хук `useState` из React: ```js{1} import React, { useState } from 'react'; @@ -98,17 +98,17 @@ function Example() { } ``` -**What is a Hook?** A Hook is a special function that lets you "hook into" React features. For example, `useState` is a Hook that lets you add React state to function components. We'll learn other Hooks later. +**Что такое хук?** Хук — это специальная функция, которая позволяет «подцепиться» к возможностям React. Например, хук `useState` предоставляет функциональным компонентам доступ к состоянию React. Мы узнаем про другие хуки чуть позже. -**When would I use a Hook?** If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component. We're going to do that right now! +**Когда применить хук?** Раньше, если вы писали функциональный компонент и осознавали, что вам нужно наделить его состоянием, вам приходилось превращать этот компонент в класс. Теперь же вы можете использовать хук внутри существующего функционального компонента. Мы покажем это прямо сейчас! ->Note: +>Примечание: > ->There are some special rules about where you can and can't use Hooks within a component. We'll learn them in [Rules of Hooks](/docs/hooks-rules.html). +>Есть специальные правила о том, где можно, а где нельзя использовать хуки внутри компонента. Их мы изучим в главе [Правила хуков](/docs/hooks-rules.html). -## Declaring a State Variable {#declaring-a-state-variable} +## Объявление переменной состояния {#declaring-a-state-variable} -In a class, we initialize the `count` state to `0` by setting `this.state` to `{ count: 0 }` in the constructor: +Допустим, мы хотим инициализировать в классе состояние `count` значением `0`. Для этого в его конструкторе присваиваем `this.state` объект `{ count: 0 }`: ```js{4-6} class Example extends React.Component { @@ -120,76 +120,76 @@ class Example extends React.Component { } ``` -In a function component, we have no `this`, so we can't assign or read `this.state`. Instead, we call the `useState` Hook directly inside our component: +В функциональном компоненте нам недоступен `this`, поэтому мы не можем задать или считать состояние через `this.state`. Вместо этого мы вызываем хук `useState` напрямую изнутри нашего компонента. ```js{4,5} import React, { useState } from 'react'; function Example() { - // Declare a new state variable, which we'll call "count" + // Объявление новой переменной состояния «count» const [count, setCount] = useState(0); ``` -**What does calling `useState` do?** It declares a "state variable". Our variable is called `count` but we could call it anything else, like `banana`. This is a way to "preserve" some values between the function calls — `useState` is a new way to use the exact same capabilities that `this.state` provides in a class. Normally, variables "disappear" when the function exits but state variables are preserved by React. +**Что делает вызов `useState`?** Он объявляет «переменную состояния». Мы называли переменную `count`, но могли дать ей любое имя, хоть `банан`. Таким образом мы можем «сохранить» некоторые значения между вызовами функции. `useState` это новый способ использовать те же возможности, что даёт `this.state` в классах. Обычно переменные «исчезают» при выходе из функции. К переменным состояния это не относится, потому что их сохраняет React. -**What do we pass to `useState` as an argument?** The only argument to the `useState()` Hook is the initial state. Unlike with classes, the state doesn't have to be an object. We can keep a number or a string if that's all we need. In our example, we just want a number for how many times the user clicked, so pass `0` as initial state for our variable. (If we wanted to store two different values in state, we would call `useState()` twice.) +**Какие аргументы передавать `useState`?** Единственный аргумент `useState` это исходное состояние. В отличие от случая с классами, состояние может быть и не объектом, а строкой или числом, если нам так удобно. Поскольку в нашем примере отслеживается количество сделанных пользователем кликов, мы передаём `0` в качестве исходного значения переменной. (Если нам нужно было бы хранить два разных значения в состоянии, то пришлось бы вызвать `useState()` дважды.) -**What does `useState` return?** It returns a pair of values: the current state and a function that updates it. This is why we write `const [count, setCount] = useState()`. This is similar to `this.state.count` and `this.setState` in a class, except you get them in a pair. If you're not familiar with the syntax we used, we'll come back to it [at the bottom of this page](/docs/hooks-state.html#tip-what-do-square-brackets-mean). +**Что возвращается из `useState`?** Вызов `useState` вернёт пару значений: текущее состояние и функцию, обновляющую состояние. Поэтому мы пишем `const [count, setCount] = useState()`. Это похоже на `this.state.count` и `this.setState` в классах, с той лишь разницей, что сейчас мы принимаем их сразу в паре. Если вам незнаком использованный синтаксис, мы вернёмся к нему [ближе к концу страницы](/docs/hooks-state.html#tip-what-do-square-brackets-mean). -Now that we know what the `useState` Hook does, our example should make more sense: +Теперь мы знаем, что делает `useState`, и пример должен быть ясен: ```js{4,5} import React, { useState } from 'react'; function Example() { - // Declare a new state variable, which we'll call "count" + // Объявление новой переменной состояния «count» const [count, setCount] = useState(0); ``` -We declare a state variable called `count`, and set it to `0`. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current `count`, we can call `setCount`. +Мы объявляем переменную состояния `count` и устанавливаем ей значение `0`. React будет помнить текущее (наиболее свежее) значение между рендерингами и передавать его нашей функции. Если мы захотим изменить `count`, мы вызовем `setCount`. ->Note +>Примечание > ->You might be wondering: why is `useState` not named `createState` instead? +>Может быть, вы спросите себя, почему `useState` не назвали `createState`? > ->"Create" wouldn't be quite accurate because the state is only created the first time our component renders. During the next renders, `useState` gives us the current state. Otherwise it wouldn't be "state" at all! There's also a reason why Hook names *always* start with `use`. We'll learn why later in the [Rules of Hooks](/docs/hooks-rules.html). +>Слово «сreate» («создать») было бы не совсем точно, потому что состояние создаётся только в момент, когда компонент рендерится впервые. В последующие же рендеринги `useState` возвращает текущее состояние. Иначе не существовало бы «состояния» как такового. Названия всех хуков начинаются с «use» тоже неспроста. О причине мы узнаем из [Правил хуков](/docs/hooks-rules.html). -## Reading State {#reading-state} +## Чтение состояния {#reading-state} -When we want to display the current count in a class, we read `this.state.count`: +Когда мы хотим отобразить текущее состояние счётчика в классе, мы обращаемся к `this.state.count`: ```js -

You clicked {this.state.count} times

+

Вы кликнули {this.state.count} раз(а)

``` -In a function, we can use `count` directly: +В функции же мы можем использовать `count` напрямую: ```js -

You clicked {count} times

+

Вы кликнули {count} раз(а)

``` -## Updating State {#updating-state} +## Обновление состояния {#updating-state} -In a class, we need to call `this.setState()` to update the `count` state: +В классе мы вызываем `this.setState()`, когда надо обновить состояние `count`: ```js{1} ``` -In a function, we already have `setCount` and `count` as variables so we don't need `this`: +В функции нам не нужен `this`, потому что `setCount` и `count` уже доступны как переменные: ```js{1} ``` -## Recap {#recap} +## Резюме {#recap} -Let's now **recap what we learned line by line** and check our understanding. +Давайте **построчно пробежимся по тому, что мы выучили** и проверим наши знания: