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
Copy file name to clipboardExpand all lines: src/content/reference/rsc/server-components.md
+49-49Lines changed: 49 additions & 49 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,42 +4,42 @@ title: Server Components
4
4
5
5
<RSC>
6
6
7
-
Server Components are for use in[React Server Components](/learn/start-a-new-react-project#bleeding-edge-react-frameworks).
7
+
Server Components предназначены для использования в[React Server Components](/learn/start-a-new-react-project#bleeding-edge-react-frameworks).
8
8
9
9
</RSC>
10
10
11
11
<Intro>
12
12
13
-
Server Components are a new type of Component that renders ahead of time, before bundling, in an environment separate from your client app or SSR server.
13
+
Server Components — это новый тип компонентов, которые рендерятся заранее, до сборки бандла, в среде, отдельной от вашего клиентского приложения или SSR-сервера.
14
14
15
15
</Intro>
16
16
17
-
This separate environment is the "server" in React Server Components. Server Components can run once at build time on your CI server, or they can be run for each request using a web server.
17
+
Эта отдельная среда — «сервер» в React Server Components. Server Components могут запускаться один раз во время сборки на вашем CI-сервере или для каждого запроса с помощью веб-сервера.
18
18
19
19
<InlineToc />
20
20
21
21
<Note>
22
22
23
-
#### How do I build support for Server Components? {/*how-do-i-build-support-for-server-components*/}
23
+
#### Как мне реализовать поддержку Server Components? {/*how-do-i-build-support-for-server-components*/}
24
24
25
-
While React Server Components in React 19 are stable and will not break between minor versions, the underlying APIs used to implement a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x.
25
+
Хотя React Server Components в React 19 стабильны и не будут ломаться между минорными версиями, базовые API, используемые для реализации бандлера или фреймворка React Server Components, не следуют semver и могут ломаться между минорными версиями в React 19.x.
26
26
27
-
To support React Server Components as a bundler or framework, we recommend pinning to a specific React version, or using the Canary release. We will continue working with bundlers and frameworks to stabilize the APIs used to implement React Server Components in the future.
27
+
Для поддержки React Server Components в качестве бандлера или фреймворка мы рекомендуем зафиксировать конкретную версию React или использовать Canary-релиз. Мы продолжим работать с бандлерами и фреймворками над стабилизацией API, используемых для реализации React Server Components, в будущем.
28
28
29
29
</Note>
30
30
31
-
### Server Components without a Server {/*server-components-without-a-server*/}
32
-
Server components can run at build time to read from the filesystem or fetch static content, so a web server is not required. For example, you may want to read static data from a content management system.
31
+
### Server Components без сервера {/*server-components-without-a-server*/}
32
+
Server Components могут запускаться во время сборки для чтения из файловой системы или получения статического контента, поэтому веб-сервер не требуется. Например, вы можете захотеть прочитать статические данные из системы управления контентом.
33
33
34
-
Without Server Components, it's common to fetch static data on the client with an Effect:
34
+
Без Server Components часто приходится получать статические данные на клиенте с помощью Effect:
This pattern means users need to download and parse an additional 75K (gzipped) of libraries, and wait for a second request to fetch the data after the page loads, just to render static content that will not change for the lifetime of the page.
61
+
Этот шаблон означает, что пользователи должны загрузить и разобрать дополнительные 75K (gzipped) библиотек и дождаться второго запроса для получения данных после загрузки страницы, только чтобы отобразить статический контент, который не изменится в течение всего времени жизни страницы.
62
62
63
-
With Server Components, you can render these components once at build time:
63
+
С помощью Server Components вы можете отрендерить эти компоненты один раз во время сборки:
64
64
65
65
```js
66
-
importmarkedfrom'marked'; //Not included in bundle
67
-
importsanitizeHtmlfrom'sanitize-html'; //Not included in bundle
66
+
importmarkedfrom'marked'; //Не включено в бандл
67
+
importsanitizeHtmlfrom'sanitize-html'; //Не включено в бандл
68
68
69
69
asyncfunctionPage({page}) {
70
-
//NOTE: loads *during* render, when the app is built.
70
+
//ПРИМЕЧАНИЕ: загружается *во время* рендера, когда приложение собирается.
71
71
constcontent=awaitfile.readFile(`${page}.md`);
72
72
73
73
return<div>{sanitizeHtml(marked(content))}</div>;
74
74
}
75
75
```
76
76
77
-
The rendered output can then be server-side rendered (SSR) to HTML and uploaded to a CDN. When the app loads, the client will not see the original `Page`component, or the expensive libraries for rendering the markdown. The client will only see the rendered output:
77
+
Полученный результат затем может быть отрендерен серверной стороной (SSR) в HTML и загружен на CDN. Когда приложение загружается, клиент не увидит исходный компонент `Page`или ресурсоемкие библиотеки для рендеринга markdown. Клиент увидит только результат рендеринга:
78
78
79
79
```js
80
-
<div><!-- html for markdown --></div>
80
+
<div><!-- html для markdown --></div>
81
81
```
82
82
83
-
This means the content is visible during first page load, and the bundle does not include the expensive libraries needed to render the static content.
83
+
Это означает, что контент виден во время первой загрузки страницы, а бандл не включает ресурсоемкие библиотеки, необходимые для рендеринга статического контента.
84
84
85
85
<Note>
86
86
87
-
You may notice that the Server Component above is an async function:
87
+
Вы можете заметить, что приведенный выше Server Component является асинхронной функцией:
88
88
89
89
```js
90
90
asyncfunctionPage({page}) {
91
91
//...
92
92
}
93
93
```
94
94
95
-
Async Components are a new feature of Server Components that allow you to `await`in render.
95
+
Async Components — это новая функция Server Components, которая позволяет использовать `await`во время рендера.
96
96
97
-
See[Async components with Server Components](#async-components-with-server-components)below.
97
+
См.[Async components with Server Components](#async-components-with-server-components)ниже.
98
98
99
99
</Note>
100
100
101
-
### Server Components with a Server {/*server-components-with-a-server*/}
102
-
Server Components can also run on a web server during a request for a page, letting you access your data layer without having to build an API. They are rendered before your application is bundled, and can pass data and JSX as props to Client Components.
101
+
### Server Components с сервером {/*server-components-with-a-server*/}
102
+
Server Components также могут запускаться на веб-сервере во время запроса страницы, позволяя вам получить доступ к вашему слою данных без необходимости создавать API. Они рендерятся до того, как ваше приложение будет собрано, и могут передавать данные и JSX в качестве пропсов клиентским компонентам.
103
103
104
-
Without Server Components, it's common to fetch dynamic data on the client in an Effect:
104
+
Без Server Components часто приходится получать динамические данные на клиенте в Effect:
105
105
106
106
```js
107
107
// bundle.js
108
108
functionNote({id}) {
109
109
const [note, setNote] =useState('');
110
-
//NOTE: loads *after* first render.
110
+
//ПРИМЕЧАНИЕ: загружается *после* первого рендера.
With Server Components, you can read the data and render it in the component:
153
+
С помощью Server Components вы можете получить данные и отрендерить их в компоненте:
154
154
155
155
```js
156
156
importdbfrom'./database';
157
157
158
158
asyncfunctionNote({id}) {
159
-
//NOTE: loads *during* render.
159
+
//ПРИМЕЧАНИЕ: загружается *во время* рендера.
160
160
constnote=awaitdb.notes.get(id);
161
161
return (
162
162
<div>
@@ -167,14 +167,14 @@ async function Note({id}) {
167
167
}
168
168
169
169
asyncfunctionAuthor({id}) {
170
-
//NOTE: loads *after* Note,
171
-
//but is fast if data is co-located.
170
+
//ПРИМЕЧАНИЕ: загружается *после* Note,
171
+
//но быстро, если данные находятся рядом.
172
172
constauthor=awaitdb.authors.get(id);
173
173
return<span>By: {author.name}</span>;
174
174
}
175
175
```
176
176
177
-
The bundler then combines the data, rendered Server Components and dynamic Client Components into a bundle. Optionally, that bundle can then be server-side rendered (SSR) to create the initial HTML for the page. When the page loads, the browser does not see the original `Note`and`Author` components; only the rendered output is sent to the client:
177
+
Затем бандлер объединяет данные, отрендеренные Server Components и динамические Client Components в бандл. При желании этот бандл может быть отрендерен серверной стороной (SSR) для создания начального HTML-кода страницы. Когда страница загружается, браузер не видит исходные компоненты `Note`и`Author`; клиенту отправляется только результат рендеринга:
178
178
179
179
```js
180
180
<div>
@@ -183,24 +183,24 @@ The bundler then combines the data, rendered Server Components and dynamic Clien
183
183
</div>
184
184
```
185
185
186
-
Server Components can be made dynamic by re-fetching them from a server, where they can access the data and render again. This new application architecture combines the simple “request/response” mental model of server-centric Multi-Page Apps with the seamless interactivity of client-centric Single-Page Apps, giving you the best of both worlds.
186
+
Server Components могут быть сделаны динамическими путем повторного получения их с сервера, где они могут получить доступ к данным и снова отрендериться. Эта новая архитектура приложения сочетает простую модель «запрос/ответ» серверно-ориентированных многостраничных приложений с бесшовной интерактивностью клиентско-ориентированных одностраничных приложений, давая вам лучшее из обоих миров.
187
187
188
-
### Adding interactivity to Server Components {/*adding-interactivity-to-server-components*/}
188
+
### Добавление интерактивности к Server Components {/*adding-interactivity-to-server-components*/}
189
189
190
-
Server Components are not sent to the browser, so they cannot use interactive APIs like`useState`. To add interactivity to Server Components, you can compose them with Client Component using the`"use client"` directive.
190
+
Server Components не отправляются в браузер, поэтому они не могут использовать интерактивные API, такие как`useState`. Чтобы добавить интерактивность к Server Components, вы можете комбинировать их с Client Components, используя директиву`"use client"`.
191
191
192
192
<Note>
193
193
194
-
#### There is no directive for Server Components. {/*there-is-no-directive-for-server-components*/}
194
+
#### Для Server Components нет директивы. {/*there-is-no-directive-for-server-components*/}
195
195
196
-
A common misunderstanding is that Server Components are denoted by `"use server"`, but there is no directive for Server Components. The`"use server"`directive is used for Server Functions.
196
+
Распространенное заблуждение заключается в том, что Server Components обозначаются `"use server"`, но для Server Components директивы нет. Директива`"use server"`используется для Server Functions.
197
197
198
-
For more info, see the docs for[Directives](/reference/rsc/directives).
198
+
Для получения дополнительной информации см. документацию по[Directives](/reference/rsc/directives).
199
199
200
200
</Note>
201
201
202
202
203
-
In the following example, the `Notes` Server Component imports an `Expandable` Client Component that uses state to toggle its `expanded` state:
203
+
В следующем примере `Notes` Server Component импортирует `Expandable` Client Component, который использует состояние для переключения своего состояния `expanded`:
204
204
```js
205
205
// Server Component
206
206
importExpandablefrom'./Expandable';
@@ -237,11 +237,11 @@ export default function Expandable({children}) {
237
237
}
238
238
```
239
239
240
-
This works by first rendering `Notes`as a Server Component, and then instructing the bundler to create a bundle for the Client Component `Expandable`. In the browser, the Client Components will see output of the Server Components passed as props:
240
+
Это работает следующим образом: сначала рендерится `Notes`как Server Component, а затем бандлеру дается указание создать бандл для Client Component `Expandable`. В браузере Client Components увидят результат рендеринга Server Components, переданный в качестве пропсов:
241
241
242
242
```js
243
243
<head>
244
-
<!--the bundle for Client Components -->
244
+
<!--бандл для Client Components -->
245
245
<script src="bundle.js"/>
246
246
</head>
247
247
<body>
@@ -259,19 +259,19 @@ This works by first rendering `Notes` as a Server Component, and then instructin
259
259
260
260
### Async components with Server Components {/*async-components-with-server-components*/}
261
261
262
-
Server Components introduce a new way to write Components using async/await. When you `await`in an async component, React will suspend and wait for the promise to resolve before resuming rendering. This works across server/client boundaries with streaming support for Suspense.
262
+
Server Components представляют новый способ написания компонентов с использованием async/await. Когда вы используете `await`в асинхронном компоненте, React приостанавливает выполнение и ждет разрешения промиса перед возобновлением рендеринга. Это работает между границами сервера и клиента с поддержкой потоковой передачи для Suspense.
263
263
264
-
You can even create a promise on the server, and await it on the client:
264
+
Вы можете даже создать промис на сервере и дождаться его на клиенте:
265
265
266
266
```js
267
267
// Server Component
268
268
importdbfrom'./database';
269
269
270
270
asyncfunctionPage({id}) {
271
-
//Will suspend the Server Component.
271
+
//Приостановит выполнение Server Component.
272
272
constnote=awaitdb.notes.get(id);
273
273
274
-
//NOTE: not awaited, will start here and await on the client.
274
+
//ПРИМЕЧАНИЕ: не дожидается, начнется здесь и будет ждать на клиенте.
275
275
constcommentsPromise=db.comments.get(note.id);
276
276
return (
277
277
<div>
@@ -290,13 +290,13 @@ async function Page({id}) {
290
290
import {use} from'react';
291
291
292
292
functionComments({commentsPromise}) {
293
-
//NOTE: this will resume the promise from the server.
294
-
//It will suspend until the data is available.
293
+
//ПРИМЕЧАНИЕ: это возобновит промис с сервера.
294
+
//Будет приостановлено до тех пор, пока данные не станут доступны.
295
295
constcomments=use(commentsPromise);
296
296
returncomments.map(commment=><p>{comment}</p>);
297
297
}
298
298
```
299
299
300
-
The`note`content is important data for the page to render, so we `await` it on the server. The comments are below the fold and lower-priority, so we start the promise on the server, and wait for it on the client with the`use` API. This will Suspend on the client, without blocking the `note` content from rendering.
300
+
Контент`note`является важными данными для рендеринга страницы, поэтому мы ждем его на сервере. Комментарии находятся ниже основной части страницы и имеют более низкий приоритет, поэтому мы запускаем промис на сервере и ждем его на клиенте с помощью API`use`. Это вызовет Suspend на клиенте, не блокируя рендеринг контента `note`.
301
301
302
-
Since async components are not supported on the client, we await the promise with`use`.
302
+
Поскольку асинхронные компоненты не поддерживаются на клиенте, мы ожидаем промис с помощью`use`.
0 commit comments