Skip to content

Commit 56e5875

Browse files
committed
add useOptimistic translation
1 parent 805b597 commit 56e5875

File tree

1 file changed

+20
-20
lines changed

1 file changed

+20
-20
lines changed

src/content/reference/react/useOptimistic.md

+20-20
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ canary: true
55

66
<Canary>
77

8-
The `useOptimistic` Hook is currently only available in React's canary and experimental channels. Learn more about [React's release channels here](/community/versioning-policy#all-release-channels).
8+
Хук `useOptimistic` сейчас доступен только в React canary и экспериментальных каналах. Узнать больше о релизаx React можно [здесь](/community/versioning-policy#all-release-channels).
99

1010
</Canary>
1111

1212
<Intro>
1313

14-
`useOptimistic` is a React Hook that lets you optimistically update the UI.
14+
`useOptimistic` это хук, который позволяет оптимистично обновлять UI.
1515

1616
```js
1717
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);
@@ -23,13 +23,13 @@ The `useOptimistic` Hook is currently only available in React's canary and exper
2323

2424
---
2525

26-
## Reference {/*reference*/}
26+
## Справочник {/*reference*/}
2727

2828
### `useOptimistic(state, updateFn)` {/*use*/}
2929

30-
`useOptimistic` is a React hook that lets you show a different state while an async action is underway. It accepts some state as an argument and returns a copy of that state that can be different during the duration of an async action such as a network request. You provide a function that takes the current state and the input to the action, and returns the optimistic state to be used while the action is pending.
30+
`useOptimistic` --это хук React, который позволяет показать другое состояние пока выполняется какое-то асинхронное действие. Он принимает состояние, которое может отличаться во время выполнения асинхронного действия, например таким действием может быть сетевой запрос. Вы передаёте функцию, которая принимает текущее состояние и входные параметры для какого-то действия, и возвращает оптимистичное состояние, которое используется пока действие находится режиме ожидания.
3131

32-
This state is called the "optimistic" state because it is usually used to immediately present the user with the result of performing an action, even though the action actually takes time to complete.
32+
Такое состояние называется "оптимистичным" состоянием, потому что обычно используется для того, чтобы показать результат выполнения действия как можно быстрее, даже если для завершения обычно требуется время.
3333

3434
```js
3535
import { useOptimistic } from 'react';
@@ -39,35 +39,35 @@ function AppContainer() {
3939
state,
4040
// updateFn
4141
(currentState, optimisticValue) => {
42-
// merge and return new state
43-
// with optimistic value
42+
// объединить и вернуть новое состояние
43+
// с оптимистичным значением
4444
}
4545
);
4646
}
4747
```
4848

49-
[See more examples below.](#usage)
49+
[Больше примеров ниже.](#usage)
5050

51-
#### Parameters {/*parameters*/}
51+
#### Параметры {/*parameters*/}
5252

53-
* `state`: the value to be returned initially and whenever no action is pending.
54-
* `updateFn(currentState, optimisticValue)`: a function that takes the current state and the optimistic value passed to `addOptimistic` and returns the resulting optimistic state. It must be a pure function. `updateFn` takes in two parameters. The `currentState` and the `optimisticValue`. The return value will be the merged value of the `currentState` and `optimisticValue`.
53+
* `state`: значение, которое вернётся изначально, и во всех случаях, когда нет действий в состоянии ожидания.
54+
* `updateFn(currentState, optimisticValue)`: функция, которая принимает текущее состояние и оптимистичное значение, переданное в `addOptimistic`, и возвращает результирующее оптимистичное состояние. Это должна быть чистая функция. `updateFn` принимает два параметра: `currentState` и `optimisticValue`. Возвращаемое значение будет результатом объединения `currentState` и `optimisticValue`.
5555

5656

57-
#### Returns {/*returns*/}
57+
#### Возвращаемое значение {/*returns*/}
5858

59-
* `optimisticState`: The resulting optimistic state. It is equal to `state` unless an action is pending, in which case it is equal to the value returned by `updateFn`.
60-
* `addOptimistic`: `addOptimistic` is the dispatching function to call when you have an optimistic update. It takes one argument, `optimisticValue`, of any type and will call the `updateFn` with `state` and `optimisticValue`.
59+
* `optimisticState`: Результат оптимистичного состояния. Оно равно `state` до тех пор, пока действие не находится в состоянии ожидания, иначе будет равно значению, возвращённому из `updateFn`.
60+
* `addOptimistic`: `addOptimistic` --это функция-диспетчер, которая вызывается при оптимистичном обновлении. Она принимает только один аргумент `optimisticValue` любого типа и вызовет `updateFn` с параметрами `state` and `optimisticValue`.
6161

6262
---
6363

64-
## Usage {/*usage*/}
64+
## Использование {/*usage*/}
6565

66-
### Optimistically updating forms {/*optimistically-updating-with-forms*/}
66+
### Оптимистичное обновление форм {/*optimistically-updating-with-forms*/}
6767

68-
The `useOptimistic` Hook provides a way to optimistically update the user interface before a background operation, like a network request, completes. In the context of forms, this technique helps to make apps feel more responsive. When a user submits a form, instead of waiting for the server's response to reflect the changes, the interface is immediately updated with the expected outcome.
68+
Хук `useOptimistic` предоставляет возможность для оптимистичного обновление пользовательского интерфейса перед завершением работы в фоновом режиме, например, сетевого запроса. В контексте форм, эта техника помогает сделать приложение более отзывчивым. Когда пользователь отправляет форму, вместо ожидания ответа от сервера для того, чтобы показать обновление, интерфейс обновится сразу же с учётом ожидаемого результата.
6969

70-
For example, when a user types a message into the form and hits the "Send" button, the `useOptimistic` Hook allows the message to immediately appear in the list with a "Sending..." label, even before the message is actually sent to a server. This "optimistic" approach gives the impression of speed and responsiveness. The form then attempts to truly send the message in the background. Once the server confirms the message has been received, the "Sending..." label is removed.
70+
Например, когда пользователь вводит сообщение в форму и нажимает кнопку "Отправить", хук `useOptimistic` позволяет сообщению сразу отобразиться в списке с лейблом "Отправка...", ещё до того как сообщение фактически будет отправлено на сервер. Этот "оптимистичный" подход создаёт ощущение скорости и отзывчивости. Затем данные формы действительно отправляются на сервер в фоновом режиме. Как только приходит подтверждение сервера о том, что сообщение получено, лейбл "Отправка..." удаляется.
7171

7272
<Sandpack>
7373

@@ -99,12 +99,12 @@ function Thread({ messages, sendMessage }) {
9999
{optimisticMessages.map((message, index) => (
100100
<div key={index}>
101101
{message.text}
102-
{!!message.sending && <small> (Sending...)</small>}
102+
{!!message.sending && <small> (Отправка...)</small>}
103103
</div>
104104
))}
105105
<form action={formAction} ref={formRef}>
106106
<input type="text" name="message" placeholder="Hello!" />
107-
<button type="submit">Send</button>
107+
<button type="submit">Отправить</button>
108108
</form>
109109
</>
110110
);

0 commit comments

Comments
 (0)