You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
During the initial render, the <CodeStepstep={2}>deferred value</CodeStep> will be the same as the <CodeStepstep={1}>value</CodeStep> you provided.
77
+
При первом рендеринге <CodeStepstep={2}>отложенное значение</CodeStep> будет равно <CodeStepstep={1}>значению</CodeStep>, которое вы передадите.
78
78
79
-
During updates, the <CodeStepstep={2}>deferred value</CodeStep> will "lag behind" the latest <CodeStepstep={1}>value</CodeStep>. In particular, React will first re-render *without* updating the deferred value, and then try to re-render with the newly received value in background.
79
+
В следующих обновлениях <CodeStepstep={2}>отложенное значение</CodeStep> будет как бы "отставать" от актуального <CodeStepstep={1}>значения</CodeStep>. А именно: сначала React отрендерит компонент, *не обновляя* отложенное значение, а затем в фоне попытается отрендерить компонент с новым значением.
80
80
81
-
**Let's walk through an example to see when this is useful.**
81
+
**Разберём на примере, когда это может быть полезно.**
82
82
83
83
<Note>
84
84
85
-
This example assumes you use one of Suspense-enabled data sources:
85
+
Предполагается, что данные в этом примере вы получаете через источники, которые поддерживают Suspense:
86
86
87
-
-Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/)and[Next.js](https://nextjs.org/docs/advanced-features/react-18)
88
-
-Lazy-loading component code with [`lazy`](/reference/react/lazy)
87
+
-Запрашиваете данные с помощью поддерживающих Suspense фреймворков, как, например, [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/)или[Next.js](https://nextjs.org/docs/advanced-features/react-18).
88
+
-Лениво загружаете код компонентов с помощью [`lazy`](/reference/react/lazy).
89
89
90
-
[Learn more about Suspense and its limitations.](/reference/react/Suspense)
90
+
[Подробнее о Suspense и связанных с ним ограничениях.](/reference/react/Suspense)
91
91
92
92
</Note>
93
93
94
94
95
-
In this example, the`SearchResults`component [suspends](/reference/react/Suspense#displaying-a-fallback-while-content-is-loading) while fetching the search results. Try typing`"a"`, waiting for the results, and then editing it to `"ab"`. The results for `"a"`get replaced by the loading fallback.
95
+
В этом примере компонент`SearchResults`[задерживается](/reference/react/Suspense#displaying-a-fallback-while-content-is-loading), т.к. отправляет поисковый запрос. Попробуйте ввести`"a"`, дождаться результатов поиска, и затем ввести `"ab"`. На месте результатов по запросу `"a"`ненадолго появится индикатор загрузки.
96
96
97
97
<Sandpack>
98
98
@@ -120,10 +120,10 @@ export default function App() {
return<p>По запросу <i>"{query}"</i> ничего не найдено</p>;
150
150
}
151
151
return (
152
152
<ul>
@@ -284,7 +284,7 @@ input { margin: 10px; }
284
284
285
285
</Sandpack>
286
286
287
-
A common alternative UI pattern is to *defer* updating the list of results and to keep showing the previous results until the new results are ready. Call `useDeferredValue` to pass a deferred version of the query down:
287
+
Однако здесь можно применить другой частый паттерн в UI: *отложить* обновление списка результатов, продолжив показывать старые результаты, пока не подготовятся новые. Чтобы передавать в результаты поиска отложенную версию запроса, можно применить `useDeferredValue`:
288
288
289
289
```js {3,11}
290
290
exportdefaultfunctionApp() {
@@ -293,20 +293,20 @@ export default function App() {
The`query`will update immediately, so the input will display the new value. However, the`deferredQuery`will keep its previous value until the data has loaded, so `SearchResults`will show the stale results for a bit.
307
+
Значение`query`будет всегда актуальным -- соответственно и отображаемый в поле ввода запрос. Но в`deferredQuery`будет предыдущее значение запроса, пока не загрузятся новые результаты поиска -- поэтому `SearchResults`ещё некоторое время будет показывать старые результаты.
308
308
309
-
Enter `"a"` in the example below, wait for the results to load, and then edit the input to `"ab"`. Notice how instead of the Suspense fallback, you now see the stale result list until the new results have loaded:
309
+
В изменённом примере ниже введите `"a"`, дождитесь загрузки результатов поиска, и затем измените запрос на `"ab"`. Обратите внимание, что теперь, пока загружаются новые результаты, вместо индикатора загрузки (заглушки Suspense) отображаются предыдущие результаты.
310
310
311
311
<Sandpack>
312
312
@@ -335,10 +335,10 @@ export default function App() {
return<p>По запросу <i>"{query}"</i> ничего не найдено</p>;
365
365
}
366
366
return (
367
367
<ul>
@@ -501,17 +501,17 @@ input { margin: 10px; }
501
501
502
502
<DeepDive>
503
503
504
-
#### How does deferring a value work under the hood? {/*how-does-deferring-a-value-work-under-the-hood*/}
504
+
#### Как работает отложенное обновление значения? {/*how-does-deferring-a-value-work-under-the-hood*/}
505
505
506
-
You can think of it as happening in two steps:
506
+
Для простоты удобно представлять, что обновление происходит в два этапа:
507
507
508
-
1.**First, React re-renders with the new `query` (`"ab"`) but with the old `deferredQuery` (still `"a")`.**The `deferredQuery` value, which you pass to the result list, is *deferred:*it "lags behind" the `query` value.
508
+
1.**Сначала React отрендерит компонент с новым запросом `"ab"` в `query`, но пока что с отложенным `"a"` в `deferredQuery`.**Значение в `deferredQuery`, которое вы передаёте в список результатов, является *отложенным:*оно "отстаёт" от значения `query`.
509
509
510
-
2.**In background, React tries to re-render with *both*`query` and `deferredQuery` updated to `"ab"`.**If this re-render completes, React will show it on the screen. However, if it suspends (the results for `"ab"` have not loaded yet), React will abandon this rendering attempt, and retry this re-render again after the data has loaded. The user will keep seeing the stale deferred value until the data is ready.
510
+
2.**Затем в фоне React попытается ещё раз отрендерить компонент, но уже с новым запросом `"ab"` и в `query`, и в `deferredQuery`.**Если этот рендеринг выполнится до конца, то React отобразит его результаты на экране. Но если рендеринг задержится (встанет в ожидании результатов для `"ab"`), то React эту конкретную попытку прервёт, а когда результаты загрузятся, попробует снова. Пока данные не загрузились, пользователю будет показываться старое отложенное значение.
511
511
512
-
The deferred "background" rendering is interruptible. For example, if you type into the input again, React will abandon it and restart with the new value. React will always use the latest provided value.
512
+
Отложенный фоновый рендеринг можно прервать. Если, например, продолжить печатать запрос, React прервёт фоновый рендеринг и перезапустит его уже с новым вводом. React всегда будет ориентироваться только на самое последнее переданное ему значение.
513
513
514
-
Note that there is still a network request per each keystroke. What's being deferred here is displaying results (until they're ready), not the network requests themselves. Even if the user continues typing, responses for each keystroke get cached, so pressing Backspace is instant and doesn't fetch again.
514
+
В этом примере важно обратить внимание, что запросы в сеть всё ещё отправляются по каждому нажатию на клавиатуре. Откладывается здесь именно обновление результатов на экране, а не отправка в сеть запроса поиска. Просто запрос по каждому нажатию кэшируется -- поэтому по удалению символа результат уже без запроса мгновенно берётся из кэша.
0 commit comments