diff --git a/src/content/blog/2024/12/05/react-19.md b/src/content/blog/2024/12/05/react-19.md index aac80a44fb..e98a4f7527 100644 --- a/src/content/blog/2024/12/05/react-19.md +++ b/src/content/blog/2024/12/05/react-19.md @@ -2,51 +2,51 @@ title: "React v19" author: The React Team date: 2024/12/05 -description: React 19 is now available on npm! In this post, we'll give an overview of the new features in React 19, and how you can adopt them. +description: React 19 теперь доступен в npm! В этой статье мы рассмотрим новые возможности React 19 и способы их внедрения. --- -December 05, 2024 by [The React Team](/community/team) +05 декабря 2024 г. от [Команды React](/community/team) --- -### React 19 is now stable! {/*react-19-is-now-stable*/} +### React 19 теперь стабилен! {/*react-19-is-now-stable*/} -Additions since this post was originally shared with the React 19 RC in April: +Дополнения с момента первоначальной публикации этого сообщения с React 19 RC в апреле: -- **Pre-warming for suspended trees**: see [Improvements to Suspense](/blog/2024/04/25/react-19-upgrade-guide#improvements-to-suspense). -- **React DOM static APIs**: see [New React DOM Static APIs](#new-react-dom-static-apis). +- **Предварительный прогрев для подвешенных деревьев**: см. [Улучшения Suspense](/blog/2024/04/25/react-19-upgrade-guide#improvements-to-suspense). +- **Статические API React DOM**: см. [Новые статические API React DOM](#new-react-dom-static-apis). -_The date for this post has been updated to reflect the stable release date._ +_Дата этого сообщения была обновлена, чтобы отразить дату стабильного выпуска._ -React v19 is now available on npm! +React v19 теперь доступен в npm! -In our [React 19 Upgrade Guide](/blog/2024/04/25/react-19-upgrade-guide), we shared step-by-step instructions for upgrading your app to React 19. In this post, we'll give an overview of the new features in React 19, and how you can adopt them. +В нашем [Руководстве по обновлению до React 19](/blog/2024/04/25/react-19-upgrade-guide) мы поделились пошаговыми инструкциями по обновлению вашего приложения до React 19. В этом сообщении мы дадим обзор новых функций в React 19 и расскажем, как вы можете их использовать. -- [What's new in React 19](#whats-new-in-react-19) -- [Improvements in React 19](#improvements-in-react-19) -- [How to upgrade](#how-to-upgrade) +- [Что нового в React 19](#whats-new-in-react-19) +- [Улучшения в React 19](#improvements-in-react-19) +- [Как обновиться](#how-to-upgrade) -For a list of breaking changes, see the [Upgrade Guide](/blog/2024/04/25/react-19-upgrade-guide). +Список критических изменений см. в [Руководстве по обновлению](/blog/2024/04/25/react-19-upgrade-guide). --- -## What's new in React 19 {/*whats-new-in-react-19*/} +## Что нового в React 19 {/*whats-new-in-react-19*/} ### Actions {/*actions*/} -A common use case in React apps is to perform a data mutation and then update state in response. For example, when a user submits a form to change their name, you will make an API request, and then handle the response. In the past, you would need to handle pending states, errors, optimistic updates, and sequential requests manually. +Распространенный сценарий использования в приложениях React — это изменение данных с последующим обновлением состояния в ответ. Например, когда пользователь отправляет форму для изменения своего имени, вы делаете запрос к API, а затем обрабатываете ответ. В прошлом вам приходилось вручную обрабатывать состояния ожидания, ошибки, оптимистичные обновления и последовательные запросы. -For example, you could handle the pending and error state in `useState`: +Например, вы могли обрабатывать состояние ожидания и ошибки с помощью `useState`: ```js -// Before Actions +// До Actions function UpdateName({}) { const [name, setName] = useState(""); const [error, setError] = useState(null); @@ -75,12 +75,12 @@ function UpdateName({}) { } ``` -In React 19, we're adding support for using async functions in transitions to handle pending states, errors, forms, and optimistic updates automatically. +В React 19 мы добавили поддержку использования асинхронных функций в переходах для автоматической обработки состояний ожидания, ошибок, форм и оптимистичных обновлений. -For example, you can use `useTransition` to handle the pending state for you: +Например, вы можете использовать `useTransition` для автоматической обработки состояния ожидания: ```js -// Using pending state from Actions +// Использование состояния ожидания из Actions function UpdateName({}) { const [name, setName] = useState(""); const [error, setError] = useState(null); @@ -109,27 +109,27 @@ function UpdateName({}) { } ``` -The async transition will immediately set the `isPending` state to true, make the async request(s), and switch `isPending` to false after any transitions. This allows you to keep the current UI responsive and interactive while the data is changing. +Асинхронный переход немедленно установит состояние `isPending` в `true`, выполнит асинхронный запрос(ы) и установит `isPending` в `false` после всех переходов. Это позволяет вам сохранять текущий интерфейс отзывчивым и интерактивным во время изменения данных. -#### By convention, functions that use async transitions are called "Actions". {/*by-convention-functions-that-use-async-transitions-are-called-actions*/} +#### По соглашению, функции, использующие асинхронные переходы, называются "Actions". {/*by-convention-functions-that-use-async-transitions-are-called-actions*/} -Actions automatically manage submitting data for you: +Actions автоматически управляют отправкой данных за вас: -- **Pending state**: Actions provide a pending state that starts at the beginning of a request and automatically resets when the final state update is committed. -- **Optimistic updates**: Actions support the new [`useOptimistic`](#new-hook-optimistic-updates) hook so you can show users instant feedback while the requests are submitting. -- **Error handling**: Actions provide error handling so you can display Error Boundaries when a request fails, and revert optimistic updates to their original value automatically. -- **Forms**: `
` elements now support passing functions to the `action` and `formAction` props. Passing functions to the `action` props use Actions by default and reset the form automatically after submission. +- **Состояние ожидания**: Actions предоставляют состояние ожидания, которое начинается в начале запроса и автоматически сбрасывается при фиксации окончательного обновления состояния. +- **Оптимистичные обновления**: Actions поддерживают новый хук [`useOptimistic`](#new-hook-optimistic-updates), чтобы вы могли мгновенно показывать пользователям обратную связь во время отправки запросов. +- **Обработка ошибок**: Actions обеспечивают обработку ошибок, позволяя отображать Error Boundaries при сбое запроса и автоматически откатывать оптимистичные обновления к исходному значению. +- **Формы**: Элементы `` теперь поддерживают передачу функций в пропсы `action` и `formAction`. Передача функций в пропсы `action` использует Actions по умолчанию и автоматически сбрасывает форму после отправки. -Building on top of Actions, React 19 introduces [`useOptimistic`](#new-hook-optimistic-updates) to manage optimistic updates, and a new hook [`React.useActionState`](#new-hook-useactionstate) to handle common cases for Actions. In `react-dom` we're adding [`` Actions](#form-actions) to manage forms automatically and [`useFormStatus`](#new-hook-useformstatus) to support the common cases for Actions in forms. +Основываясь на Actions, React 19 представляет [`useOptimistic`](#new-hook-optimistic-updates) для управления оптимистичными обновлениями и новый хук [`React.useActionState`](#new-hook-useactionstate) для обработки распространенных случаев использования Actions. В `react-dom` мы добавляем [`` Actions](#form-actions) для автоматического управления формами и [`useFormStatus`](#new-hook-useformstatus) для поддержки распространенных случаев использования Actions в формах. -In React 19, the above example can be simplified to: +В React 19 приведенный выше пример можно упростить до: ```js -// Using Actions and useActionState +// Использование Actions и useActionState function ChangeName({ name, setName }) { const [error, submitAction, isPending] = useActionState( async (previousState, formData) => { @@ -153,56 +153,56 @@ function ChangeName({ name, setName }) { } ``` -In the next section, we'll break down each of the new Action features in React 19. +В следующем разделе мы подробно рассмотрим каждую из новых функций Actions в React 19. -### New hook: `useActionState` {/*new-hook-useactionstate*/} +### Новый хук: `useActionState` {/*new-hook-useactionstate*/} -To make the common cases easier for Actions, we've added a new hook called `useActionState`: +Чтобы упростить распространенные случаи использования Actions, мы добавили новый хук под названием `useActionState`: ```js const [error, submitAction, isPending] = useActionState( async (previousState, newName) => { const error = await updateName(newName); if (error) { - // You can return any result of the action. - // Here, we return only the error. + // Вы можете вернуть любой результат действия. + // Здесь мы возвращаем только ошибку. return error; } - // handle success + // обработка успеха return null; }, null, ); ``` -`useActionState` accepts a function (the "Action"), and returns a wrapped Action to call. This works because Actions compose. When the wrapped Action is called, `useActionState` will return the last result of the Action as `data`, and the pending state of the Action as `pending`. +`useActionState` принимает функцию ( "Action") и возвращает обернутую Action для вызова. Это работает, потому что Actions компонуются. Когда вызывается обернутая Action, `useActionState` возвращает последний результат Action как `data`, а состояние ожидания Action как `pending`. -`React.useActionState` was previously called `ReactDOM.useFormState` in the Canary releases, but we've renamed it and deprecated `useFormState`. +`React.useActionState` ранее назывался `ReactDOM.useFormState` в Canary-релизах, но мы переименовали его и устарели `useFormState`. -See [#28491](https://github.com/facebook/react/pull/28491) for more info. +См. [#28491](https://github.com/facebook/react/pull/28491) для получения дополнительной информации. -For more information, see the docs for [`useActionState`](/reference/react/useActionState). +Для получения дополнительной информации см. документацию по [`useActionState`](/reference/react/useActionState). ### React DOM: `` Actions {/*form-actions*/} -Actions are also integrated with React 19's new `` features for `react-dom`. We've added support for passing functions as the `action` and `formAction` props of ``, ``, and `