From 07e3b2a14dc446448c416bfdf483d6aa5f3c57ba Mon Sep 17 00:00:00 2001 From: Nivaldo Farias Date: Mon, 20 Jan 2025 11:09:01 -0300 Subject: [PATCH 1/5] Translate `react-19-upgrade-guide.md` to pt-br --- .../blog/2024/04/25/react-19-upgrade-guide.md | 357 +++++++++--------- 1 file changed, 178 insertions(+), 179 deletions(-) diff --git a/src/content/blog/2024/04/25/react-19-upgrade-guide.md b/src/content/blog/2024/04/25/react-19-upgrade-guide.md index 4d4355a47..f286b0bb4 100644 --- a/src/content/blog/2024/04/25/react-19-upgrade-guide.md +++ b/src/content/blog/2024/04/25/react-19-upgrade-guide.md @@ -1,86 +1,86 @@ --- -title: "React 19 Beta Upgrade Guide" +title: "Guia de Atualização para o Beta do React 19" author: Ricky Hanlon date: 2024/04/25 -description: The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible and we don't expect the changes to impact most apps. In this post, we will guide you through the steps for upgrading libraries to React 19 beta. +description: As melhorias adicionadas ao React 19 requerem algumas mudanças que quebram a compatibilidade, mas trabalhamos para tornar a atualização o mais suave possível e não esperamos que as mudanças impactem a maioria dos aplicativos. Neste post, vamos guiá-lo através das etapas para atualizar bibliotecas para a versão beta do React 19. --- -April 25, 2024 by [Ricky Hanlon](https://twitter.com/rickhanlonii) +25 de abril de 2024 por [Ricky Hanlon](https://twitter.com/rickhanlonii) --- -This beta release is for libraries to prepare for React 19. App developers should upgrade to 18.3.0 and wait for React 19 stable as we work with libraries and make changes based on feedback. +Este lançamento beta é para bibliotecas se prepararem para o React 19. Desenvolvedores de aplicativos devem atualizar para 18.3.0 e aguardar a versão estável do React 19 enquanto trabalhamos com bibliotecas e fazemos alterações com base no feedback. -The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible and we don't expect the changes to impact most apps. +As melhorias adicionadas ao React 19 requerem algumas mudanças que quebram a compatibilidade, mas trabalhamos para tornar a atualização o mais suave possível e não esperamos que as mudanças impactem a maioria dos aplicativos. -To help make the upgrade easier, today we are also publishing React 18.3. +Para ajudar a tornar a atualização mais fácil, hoje também estamos publicando o React 18.3. -#### React 18.3 has also been published {/*react-18-3*/} +#### O React 18.3 também foi publicado {/*react-18-3*/} -To help make the upgrade to React 19 easier, we've published a `react@18.3` release that is identical to 18.2 but adds warnings for deprecated APIs and other changes that are needed for React 19. +Para ajudar a facilitar a atualização para o React 19, publicamos um lançamento `react@18.3` que é idêntico ao 18.2, mas adiciona avisos para APIs obsoletas e outras mudanças necessárias para o React 19. -We recommend upgrading to React 18.3 first to help identify any issues before upgrading to React 19. +Recomendamos atualizar para o React 18.3 primeiro para ajudar a identificar quaisquer problemas antes de atualizar para o React 19. -For a list of changes in 18.3 see the [Release Notes](https://github.com/facebook/react/blob/main/CHANGELOG.md). +Para uma lista de mudanças no 18.3, consulte as [Notas de Lançamento](https://github.com/facebook/react/blob/main/CHANGELOG.md). -In this post, we will guide you through the steps for upgrading libraries to React 19 beta: +Neste post, vamos guiá-lo através das etapas para atualizar bibliotecas para a versão beta do React 19: -- [Installing](#installing) -- [Breaking changes](#breaking-changes) -- [New deprecations](#new-deprecations) -- [Notable changes](#notable-changes) -- [TypeScript changes](#typescript-changes) -- [Changelog](#changelog) +- [Instalando](#installing) +- [Mudanças quebrando a compatibilidade](#breaking-changes) +- [Novas desativações](#new-deprecations) +- [Mudanças notáveis](#notable-changes) +- [Mudanças no TypeScript](#typescript-changes) +- [Notas de versão](#changelog) -If you'd like to help us test React 19, follow the steps in this upgrade guide and [report any issues](https://github.com/facebook/react/issues/new?assignees=&labels=React+19&projects=&template=19.md&title=%5BReact+19%5D) you encounter. For a list of new features added to React 19 beta, see the [React 19 release post](/blog/2024/04/25/react-19). +Se você gostaria de nos ajudar a testar o React 19, siga os passos neste guia de atualização e [relate quaisquer problemas](https://github.com/facebook/react/issues/new?assignees=&labels=React+19&projects=&template=19.md&title=%5BReact+19%5D) que encontrar. Para uma lista de novos recursos adicionados ao React 19 beta, consulte o [post de lançamento do React 19](/blog/2024/04/25/react-19). --- -## Installing {/*installing*/} +## Instalando {/*installing*/} -#### New JSX Transform is now required {/*new-jsx-transform-is-now-required*/} +#### Novo JSX Transform agora é obrigatório {/*new-jsx-transform-is-now-required*/} -We introduced a [new JSX transform](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) in 2020 to improve bundle size and use JSX without importing React. In React 19, we're adding additional improvements like using ref as a prop and JSX speed improvements that require the new transform. +Introduzimos um [novo transformador JSX](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) em 2020 para melhorar o tamanho do pacote e usar JSX sem importar o React. No React 19, estamos adicionando melhorias adicionais, como usar ref como uma prop e melhorias de velocidade do JSX, que requerem o novo transformador. -If the new transform is not enabled, you will see this warning: +Se o novo transformador não estiver habilitado, você verá o seguinte aviso: -Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform +Seu aplicativo (ou uma de suas dependências) está usando um transformador JSX obsoleto. Atualize para o transformador JSX moderno para um desempenho mais rápido: https://react.dev/link/new-jsx-transform -We expect most apps will not be affected since the transform is enabled in most environments already. For manual instructions on how to upgrade, please see the [announcement post](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html). +Esperamos que a maioria dos aplicativos não seja afetada, pois o transformador já está habilitado na maioria dos ambientes. Para instruções manuais sobre como atualizar, consulte o [post de anúncio](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html). -To install the latest version of React and React DOM: +Para instalar a versão mais recente do React e do React DOM: ```bash npm install react@beta react-dom@beta ``` -If you're using TypeScript, you also need to update the types. Once React 19 is released as stable, you can install the types as usual from `@types/react` and `@types/react-dom`. During the beta period, the types are available in different packages which need to be enforced in your `package.json`: +Se você estiver usando TypeScript, também precisará atualizar os tipos. Assim que o React 19 for lançado como estável, você pode instalar os tipos normalmente de `@types/react` e `@types/react-dom`. Durante o período beta, os tipos estão disponíveis em pacotes diferentes que precisam ser forçados no seu `package.json`: ```json { @@ -95,47 +95,47 @@ If you're using TypeScript, you also need to update the types. Once React 19 is } ``` -We're also including a codemod for the most common replacements. See [TypeScript changes](#typescript-changes) below. +Estamos também incluindo um codemod para as substituições mais comuns. Consulte as [mudanças no TypeScript](#typescript-changes) abaixo. -## Breaking changes {/*breaking-changes*/} +## Mudanças quebrando a compatibilidade {/*breaking-changes*/} -### Errors in render are not re-thrown {/*errors-in-render-are-not-re-thrown*/} +### Erros na renderização não são re-lançados {/*errors-in-render-are-not-re-thrown*/} -In previous versions of React, errors thrown during render were caught and rethrown. In DEV, we would also log to `console.error`, resulting in duplicate error logs. +Nas versões anteriores do React, erros lançados durante a renderização eram capturados e relançados. Em DEV, também registrávamos em `console.error`, resultando em registros de erro duplicados. -In React 19, we've [improved how errors are handled](/blog/2024/04/25/react-19#error-handling) to reduce duplication by not re-throwing: +No React 19, [melhoramos como os erros são tratados](/blog/2024/04/25/react-19#error-handling) para reduzir a duplicação, não relançando: -- **Uncaught Errors**: Errors that are not caught by an Error Boundary are reported to `window.reportError`. -- **Caught Errors**: Errors that are caught by an Error Boundary are reported to `console.error`. +- **Erros Não Capturados**: Erros que não são capturados por um Boundary de Erro são relatados para `window.reportError`. +- **Erros Capturados**: Erros que são capturados por um Boundary de Erro são relatados para `console.error`. -This change should not impact most apps, but if your production error reporting relies on errors being re-thrown, you may need to update your error handling. To support this, we've added new methods to `createRoot` and `hydrateRoot` for custom error handling: +Essa mudança não deve impactar a maioria dos aplicativos, mas se sua relatória de erros em produção depende de erros sendo relançados, você pode precisar atualizar seu tratamento de erros. Para suportar isso, adicionamos novos métodos a `createRoot` e `hydrateRoot` para tratamento de erros personalizado: ```js [[1, 2, "onUncaughtError"], [2, 5, "onCaughtError"]] const root = createRoot(container, { onUncaughtError: (error, errorInfo) => { - // ... log error report + // ... registrar relatório de erro }, onCaughtError: (error, errorInfo) => { - // ... log error report + // ... registrar relatório de erro } }); ``` -For more info, see the docs for [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) and [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot). +Para mais informações, consulte a documentação para [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) e [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot). -### Removed deprecated React APIs {/*removed-deprecated-react-apis*/} +### APIs obsoletas do React removidas {/*removed-deprecated-react-apis*/} -#### Removed: `propTypes` and `defaultProps` for functions {/*removed-proptypes-and-defaultprops*/} -`PropTypes` were deprecated in [April 2017 (v15.5.0)](https://legacy.reactjs.org/blog/2017/04/07/react-v15.5.0.html#new-deprecation-warnings). +#### Removido: `propTypes` e `defaultProps` para funções {/*removed-proptypes-and-defaultprops*/} +`PropTypes` foram descontinuados em [abril de 2017 (v15.5.0)](https://legacy.reactjs.org/blog/2017/04/07/react-v15.5.0.html#new-deprecation-warnings). -In React 19, we're removing the `propType` checks from the React package, and using them will be silently ignored. If you're using `propTypes`, we recommend migrating to TypeScript or another type-checking solution. +No React 19, estamos removendo as verificações de `propType` do pacote React, e seu uso será ignorado silenciosamente. Se você estiver usando `propTypes`, recomendamos migrar para TypeScript ou outra solução de verificação de tipos. -We're also removing `defaultProps` from function components in place of ES6 default parameters. Class components will continue to support `defaultProps` since there is no ES6 alternative. +Estamos também removendo `defaultProps` de componentes de função em lugar de parâmetros padrão do ES6. Componentes de classe continuarão a suportar `defaultProps`, já que não há alternativa no ES6. ```js -// Before +// Antes import PropTypes from 'prop-types'; function Heading({text}) { @@ -149,7 +149,7 @@ Heading.defaultProps = { }; ``` ```ts -// After +// Depois interface Props { text?: string; } @@ -158,16 +158,16 @@ function Heading({text = 'Hello, world!'}: Props) { } ``` -#### Removed: Legacy Context using `contextTypes` and `getChildContext` {/*removed-removing-legacy-context*/} +#### Removido: Contexto Legado usando `contextTypes` e `getChildContext` {/*removed-removing-legacy-context*/} -Legacy Context was deprecated in [October 2018 (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html). +O Contexto Legado foi descontinuado em [outubro de 2018 (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html). -Legacy Context was only available in class components using the APIs `contextTypes` and `getChildContext`, and was replaced with `contextType` due to subtle bugs that were easy to miss. In React 19, we're removing Legacy Context to make React slightly smaller and faster. +O Contexto Legado estava disponível apenas em componentes de classe usando as APIs `contextTypes` e `getChildContext`, e foi substituído por `contextType` devido a bugs sutis que eram fáceis de perder. No React 19, estamos removendo o Contexto Legado para tornar o React um pouco menor e mais rápido. -If you're still using Legacy Context in class components, you'll need to migrate to the new `contextType` API: +Se você ainda estiver usando o Contexto Legado em componentes de classe, precisará migrar para a nova API `contextType`: ```js {5-11,19-21} -// Before +// Antes import PropTypes from 'prop-types'; class Parent extends React.Component { @@ -196,7 +196,7 @@ class Child extends React.Component { ``` ```js {2,7,9,15} -// After +// Depois const FooContext = React.createContext(); class Parent extends React.Component { @@ -218,15 +218,15 @@ class Child extends React.Component { } ``` -#### Removed: string refs {/*removed-string-refs*/} -String refs were deprecated in [March, 2018 (v16.3.0)](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html). +#### Removido: refs de string {/*removed-string-refs*/} +Refs de string foram descontinuados em [março de 2018 (v16.3.0)](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html). -Class components supported string refs before being replaced by ref callbacks due to [multiple downsides](https://github.com/facebook/react/issues/1373). In React 19, we're removing string refs to make React simpler and easier to understand. +Componentes de classe suportavam refs de string antes de serem substituídos por callbacks de ref devido a [vários contratempos](https://github.com/facebook/react/issues/1373). No React 19, estamos removendo refs de string para simplificar o React e torná-lo mais fácil de entender. -If you're still using string refs in class components, you'll need to migrate to ref callbacks: +Se você ainda estiver usando refs de string em componentes de classe, precisará migrar para callbacks de ref: ```js {4,8} -// Before +// Antes class MyComponent extends React.Component { componentDidMount() { this.refs.input.focus(); @@ -239,7 +239,7 @@ class MyComponent extends React.Component { ``` ```js {4,8} -// After +// Depois class MyComponent extends React.Component { componentDidMount() { this.input.focus(); @@ -253,49 +253,49 @@ class MyComponent extends React.Component { -To help with the migration, we will be publishing a [react-codemod](https://github.com/reactjs/react-codemod/#string-refs) to automatically replace string refs with `ref` callbacks. Follow [this PR](https://github.com/reactjs/react-codemod/pull/309) for updates and to try it out. +Para ajudar com a migração, publicaremos um [react-codemod](https://github.com/reactjs/react-codemod/#string-refs) para substituir automaticamente refs de string por callbacks de `ref`. Siga [este PR](https://github.com/reactjs/react-codemod/pull/309) para atualizações e para testá-lo. -#### Removed: Module pattern factories {/*removed-module-pattern-factories*/} -Module pattern factories were deprecated in [August 2019 (v16.9.0)](https://legacy.reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-module-pattern-factories). +#### Removido: Fábricas de padrão de módulo {/*removed-module-pattern-factories*/} +Fábricas de padrão de módulo foram descontinuadas em [agosto de 2019 (v16.9.0)](https://legacy.reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-module-pattern-factories). -This pattern was rarely used and supporting it causes React to be slightly larger and slower than necessary. In React 19, we're removing support for module pattern factories, and you'll need to migrate to regular functions: +Esse padrão era raramente usado e seu suporte fazia com que o React fosse ligeiramente maior e mais lento do que o necessário. No React 19, estamos removendo o suporte a fábricas de padrão de módulo, e você precisará migrar para funções regulares: ```js -// Before +// Antes function FactoryComponent() { return { render() { return
; } } } ``` ```js -// After +// Depois function FactoryComponent() { return
; } ``` -#### Removed: `React.createFactory` {/*removed-createfactory*/} -`createFactory` was deprecated in [February 2020 (v16.13.0)](https://legacy.reactjs.org/blog/2020/02/26/react-v16.13.0.html#deprecating-createfactory). +#### Removido: `React.createFactory` {/*removed-createfactory*/} +`createFactory` foi descontinuado em [fevereiro de 2020 (v16.13.0)](https://legacy.reactjs.org/blog/2020/02/26/react-v16.13.0.html#deprecating-createfactory). -Using `createFactory` was common before broad support for JSX, but it's rarely used today and can be replaced with JSX. In React 19, we're removing `createFactory` and you'll need to migrate to JSX: +Usar `createFactory` era comum antes do amplo suporte ao JSX, mas hoje é raramente utilizado e pode ser substituído por JSX. No React 19, estamos removendo `createFactory` e você precisará migrar para JSX: ```js -// Before +// Antes import { createFactory } from 'react'; const button = createFactory('button'); ``` ```js -// After +// Depois const button =