Skip to content

Commit 2105219

Browse files
authored
Merge pull request #974 from rLukoyanov/main
Translate useOptimistic
2 parents 2999f38 + ba1344d commit 2105219

File tree

1 file changed

+21
-21
lines changed

1 file changed

+21
-21
lines changed

src/content/reference/react/useOptimistic.md

+21-21
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 и является экспериментальным. Узнайте больше о [релизах 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` -- это хук React, который позволяет оптимистично обновлять 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,20 +99,20 @@ 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
);
111111
}
112112

113113
export default function App() {
114114
const [messages, setMessages] = useState([
115-
{ text: "Hello there!", sending: false, key: 1 }
115+
{ text: "Привет!", sending: false, key: 1 }
116116
]);
117117
async function sendMessage(formData) {
118118
const sentMessage = await deliverMessage(formData.get("message"));

0 commit comments

Comments
 (0)