diff --git a/src/content/reference/rsc/use-server.md b/src/content/reference/rsc/use-server.md index 58b1f0ee15..a195a2a3a1 100644 --- a/src/content/reference/rsc/use-server.md +++ b/src/content/reference/rsc/use-server.md @@ -2,17 +2,16 @@ title: "'use server'" titleForTitleTag: "'use server' directive" --- - -`'use server'` is for use with [using React Server Components](/reference/rsc/server-components). +`'use server'` используется с [использованием React Server Components](/reference/rsc/server-components). -`'use server'` marks server-side functions that can be called from client-side code. +`'use server'` помечает серверные функции, которые можно вызывать из клиентского кода. @@ -20,11 +19,11 @@ titleForTitleTag: "'use server' directive" --- -## Reference {/*reference*/} +## Справочник {/*reference*/} ### `'use server'` {/*use-server*/} -Add `'use server'` at the top of an async function body to mark the function as callable by the client. We call these functions [_Server Functions_](/reference/rsc/server-functions). +Добавьте `'use server'` в начало тела асинхронной функции, чтобы пометить её как доступную для вызова клиентом. Мы называем такие функции [_Server Functions_](/reference/rsc/server-functions). ```js {2} async function addToCart(data) { @@ -33,78 +32,78 @@ async function addToCart(data) { } ``` -When calling a Server Function on the client, it will make a network request to the server that includes a serialized copy of any arguments passed. If the Server Function returns a value, that value will be serialized and returned to the client. +При вызове Server Function с клиента будет выполнен сетевой запрос на сервер, включающий сериализованную копию всех переданных аргументов. Если Server Function возвращает значение, это значение будет сериализовано и возвращено клиенту. -Instead of individually marking functions with `'use server'`, you can add the directive to the top of a file to mark all exports within that file as Server Functions that can be used anywhere, including imported in client code. +Вместо того чтобы помечать функции по отдельности с помощью `'use server'`, вы можете добавить директиву в начало файла, чтобы пометить все экспорты в этом файле как Server Functions, которые можно использовать где угодно, в том числе импортировать в клиентский код. -#### Caveats {/*caveats*/} -* `'use server'` must be at the very beginning of their function or module; above any other code including imports (comments above directives are OK). They must be written with single or double quotes, not backticks. -* `'use server'` can only be used in server-side files. The resulting Server Functions can be passed to Client Components through props. See supported [types for serialization](#serializable-parameters-and-return-values). -* To import a Server Functions from [client code](/reference/rsc/use-client), the directive must be used on a module level. -* Because the underlying network calls are always asynchronous, `'use server'` can only be used on async functions. -* Always treat arguments to Server Functions as untrusted input and authorize any mutations. See [security considerations](#security). -* Server Functions should be called in a [Transition](/reference/react/useTransition). Server Functions passed to [`
`](/reference/react-dom/components/form#props) or [`formAction`](/reference/react-dom/components/input#props) will automatically be called in a transition. -* Server Functions are designed for mutations that update server-side state; they are not recommended for data fetching. Accordingly, frameworks implementing Server Functions typically process one action at a time and do not have a way to cache the return value. +#### Ограничения {/*caveats*/} +* `'use server'` должна находиться в самом начале функции или модуля; выше любого другого кода, включая импорты (комментарии перед директивами допустимы). Она должна быть написана в одинарных или двойных кавычках, а не в обратных. +* `'use server'` может использоваться только в серверных файлах. Полученные Server Functions могут быть переданы в Client Components через пропсы. См. поддерживаемые [типы для сериализации](#serializable-parameters-and-return-values). +* Для импорта Server Functions из [клиентского кода](/reference/rsc/use-client) директива должна использоваться на уровне модуля. +* Поскольку базовые сетевые вызовы всегда асинхронны, `'use server'` может использоваться только с асинхронными функциями. +* Всегда относитесь к аргументам Server Functions как к недоверенным входным данным и авторизуйте любые мутации. См. [соображения безопасности](#security). +* Server Functions должны вызываться в [Transition](/reference/react/useTransition). Server Functions, переданные в [``](/reference/react-dom/components/form#props) или [`formAction`](/reference/react-dom/components/input#props), будут автоматически вызваны в переходе. +* Server Functions предназначены для мутаций, обновляющих серверное состояние; они не рекомендуются для получения данных. Соответственно, фреймворки, реализующие Server Functions, обычно обрабатывают одно действие за раз и не имеют способа кэшировать возвращаемое значение. -### Security considerations {/*security*/} +### Соображения безопасности {/*security*/} -Arguments to Server Functions are fully client-controlled. For security, always treat them as untrusted input, and make sure to validate and escape arguments as appropriate. +Аргументы для Server Functions полностью контролируются клиентом. В целях безопасности всегда относитесь к ним как к недоверенным входным данным и убедитесь, что вы валидируете и экранируете аргументы по мере необходимости. -In any Server Function, make sure to validate that the logged-in user is allowed to perform that action. +В любой Server Function убедитесь, что вы проверяете, разрешено ли вошедшему в систему пользователю выполнять это действие. -To prevent sending sensitive data from a Server Function, there are experimental taint APIs to prevent unique values and objects from being passed to client code. +Чтобы предотвратить отправку конфиденциальных данных из Server Function, существуют экспериментальные API для отслеживания (taint), предотвращающие передачу уникальных значений и объектов в клиентский код. -See [experimental_taintUniqueValue](/reference/react/experimental_taintUniqueValue) and [experimental_taintObjectReference](/reference/react/experimental_taintObjectReference). +См. [experimental_taintUniqueValue](/reference/react/experimental_taintUniqueValue) и [experimental_taintObjectReference](/reference/react/experimental_taintObjectReference). -### Serializable arguments and return values {/*serializable-parameters-and-return-values*/} +### Сериализуемые аргументы и возвращаемые значения {/*serializable-parameters-and-return-values*/} -Since client code calls the Server Function over the network, any arguments passed will need to be serializable. +Поскольку клиентский код вызывает Server Function по сети, любые переданные аргументы должны быть сериализуемыми. -Here are supported types for Server Function arguments: +Вот поддерживаемые типы аргументов для Server Functions: -* Primitives +* Примитивы * [string](https://developer.mozilla.org/en-US/docs/Glossary/String) * [number](https://developer.mozilla.org/en-US/docs/Glossary/Number) * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) * [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean) * [undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined) * [null](https://developer.mozilla.org/en-US/docs/Glossary/Null) - * [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), only symbols registered in the global Symbol registry via [`Symbol.for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for) -* Iterables containing serializable values + * [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), только символы, зарегистрированные в глобальном реестре Symbol через [`Symbol.for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for) +* Итерируемые объекты, содержащие сериализуемые значения * [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) * [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) * [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) * [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) - * [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) and [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) + * [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) и [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) * [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) -* [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) instances -* Plain [objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object): those created with [object initializers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), with serializable properties -* Functions that are Server Functions +* Экземпляры [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) +* Простые [объекты](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object): созданные с помощью [инициализаторов объектов](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), с сериализуемыми свойствами +* Функции, которые являются Server Functions * [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) -Notably, these are not supported: -* React elements, or [JSX](/learn/writing-markup-with-jsx) -* Functions, including component functions or any other function that is not a Server Function -* [Classes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript) -* Objects that are instances of any class (other than the built-ins mentioned) or objects with [a null prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) -* Symbols not registered globally, ex. `Symbol('my new symbol')` -* Events from event handlers +Примечательно, что не поддерживаются: +* React-элементы или [JSX](/learn/writing-markup-with-jsx) +* Функции, включая компонентные функции или любые другие функции, не являющиеся Server Functions +* [Классы](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript) +* Объекты, являющиеся экземплярами любого класса (кроме упомянутых встроенных) или объекты с [нулевым прототипом](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) +* Символы, не зарегистрированные глобально, например `Symbol('my new symbol')` +* События от обработчиков событий -Supported serializable return values are the same as [serializable props](/reference/rsc/use-client#passing-props-from-server-to-client-components) for a boundary Client Component. +Поддерживаемые сериализуемые возвращаемые значения такие же, как [сериализуемые пропсы](/reference/rsc/use-client#passing-props-from-server-to-client-components) для граничного Client Component. -## Usage {/*usage*/} +## Использование {/*usage*/} -### Server Functions in forms {/*server-functions-in-forms*/} +### Server Functions в формах {/*server-functions-in-forms*/} -The most common use case of Server Functions will be calling functions that mutate data. On the browser, the [HTML form element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) is the traditional approach for a user to submit a mutation. With React Server Components, React introduces first-class support for Server Functions as Actions in [forms](/reference/react-dom/components/form). +Наиболее распространенным сценарием использования Server Functions будет вызов функций, изменяющих данные. В браузере элемент [HTML-формы](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) является традиционным подходом для пользователя для отправки мутации. С React Server Components React вводит первоклассную поддержку Server Functions в качестве Actions в [формах](/reference/react-dom/components/form). -Here is a form that allows a user to request a username. +Вот форма, которая позволяет пользователю запросить имя пользователя. ```js [[1, 3, "formData"]] // App.js @@ -125,15 +124,15 @@ export default function App() { } ``` -In this example `requestUsername` is a Server Function passed to a ``. When a user submits this form, there is a network request to the server function `requestUsername`. When calling a Server Function in a form, React will supply the form's [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) as the first argument to the Server Function. +В этом примере `requestUsername` — это Server Function, переданная в ``. Когда пользователь отправляет эту форму, происходит сетевой запрос к серверной функции `requestUsername`. При вызове Server Function в форме React передаст [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) формы в качестве первого аргумента Server Function. -By passing a Server Function to the form `action`, React can [progressively enhance](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement) the form. This means that forms can be submitted before the JavaScript bundle is loaded. +Передавая Server Function в `action` формы, React может [постепенно улучшать](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement) форму. Это означает, что формы могут быть отправлены до загрузки JavaScript-бандла. -#### Handling return values in forms {/*handling-return-values*/} +#### Обработка возвращаемых значений в формах {/*handling-return-values*/} -In the username request form, there might be the chance that a username is not available. `requestUsername` should tell us if it fails or not. +В форме запроса имени пользователя может возникнуть ситуация, когда имя пользователя недоступно. `requestUsername` должен сообщить нам, удалось ли это или нет. -To update the UI based on the result of a Server Function while supporting progressive enhancement, use [`useActionState`](/reference/react/useActionState). +Чтобы обновить UI на основе результата Server Function, поддерживая при этом постепенное улучшение, используйте [`useActionState`](/reference/react/useActionState). ```js // requestUsername.js @@ -171,13 +170,13 @@ function UsernameForm() { } ``` -Note that like most Hooks, `useActionState` can only be called in [client code](/reference/rsc/use-client). +Обратите внимание, что, как и большинство хуков, `useActionState` можно вызывать только в [клиентском коде](/reference/rsc/use-client). -### Calling a Server Function outside of `` {/*calling-a-server-function-outside-of-form*/} +### Вызов Server Function вне `` {/*calling-a-server-function-outside-of-form*/} -Server Functions are exposed server endpoints and can be called anywhere in client code. +Server Functions — это серверные конечные точки, и их можно вызывать из любого места в клиентском коде. -When using a Server Function outside a [form](/reference/react-dom/components/form), call the Server Function in a [Transition](/reference/react/useTransition), which allows you to display a loading indicator, show [optimistic state updates](/reference/react/useOptimistic), and handle unexpected errors. Forms will automatically wrap Server Functions in transitions. +При использовании Server Function вне [формы](/reference/react-dom/components/form) вызывайте Server Function в [Transition](/reference/react/useTransition), что позволяет отображать индикатор загрузки, показывать [оптимистичные обновления состояния](/reference/react/useOptimistic) и обрабатывать неожиданные ошибки. Формы автоматически оборачивают Server Functions в переходы. ```js {9-12} import incrementLike from './actions'; @@ -214,4 +213,4 @@ export default async function incrementLike() { } ``` -To read a Server Function return value, you'll need to `await` the promise returned. +Чтобы прочитать возвращаемое значение Server Function, вам нужно будет `await` вернуть обещание. \ No newline at end of file