Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translation of blog post: "2018-03-29-react-v16.3.0" #210

Merged
merged 8 commits into from
May 5, 2019
94 changes: 47 additions & 47 deletions content/blog/2018-03-29-react-v-16-3.md
Original file line number Diff line number Diff line change
@@ -1,95 +1,95 @@
---
title: "React v16.3.0: New lifecycles and context API"
title: "React v16.3.0: Novos ciclos de vida e API de contexto"
author: [bvaughn]
---

A few days ago, we [wrote a post about upcoming changes to our legacy lifecycle methods](/blog/2018/03/27/update-on-async-rendering.html), including gradual migration strategies. In React 16.3.0, we are adding a few new lifecycle methods to assist with that migration. We are also introducing new APIs for long requested features: an official context API, a ref forwarding API, and an ergonomic ref API.
Há alguns dias, [escrevemos uma postagem sobre as próximas mudanças em nossos métodos de ciclo de vida legados](/blog/2018/03/27/update-on-async-rendering.html), incluindo estratégias de migração gradual. No React 16.3.0, estamos adicionando alguns novos métodos de ciclo de vida para ajudar nessa migração. Também estamos introduzindo novas APIs para funcionalidades há tempo solicitadas: uma API de contexto oficial, uma API de referência de encaminhamento e uma API de referência de ergonomia.

Read on to learn more about the release.
Leia para saber mais sobre o lançamento.

## Official Context API {#official-context-api}
## API Oficial de Contexto {#official-context-api}

For many years, React has offered an experimental API for context. Although it was a powerful tool, its use was discouraged because of inherent problems in the API, and because we always intended to replace the experimental API with a better one.
Por muitos anos, o React ofereceu uma API experimental para contexto. Embora fosse uma ferramenta poderosa, seu uso foi desencorajado por causa de problemas inerentes na API, e porque sempre pretendíamos substituir a API experimental por uma melhor.

Version 16.3 introduces a new context API that is more efficient and supports both static type checking and deep updates.
A versão 16.3 introduz uma nova API de contexto que é mais eficiente e suporta tanto verificação de tipo estático quanto atualizações profundas.

> **Note**
> **Nota**
>
> The old context API will keep working for all React 16.x releases, so you will have time to migrate.
> A antiga API de contexto continuará funcionando para todas as versões do React 16.x, assim você terá tempo para migrar.

Here is an example illustrating how you might inject a "theme" using the new context API:
Aqui está um exemplo ilustrando como você pode introduzir um “tema” usando a nova API de contexto:
`embed:16-3-release-blog-post/context-example.js`

[Learn more about the new context API here.](/docs/context.html)
[Saiba mais sobre a nova API de contexto aqui.](/docs/context.html)

## `createRef` API {#createref-api}
## API `createRef` {#createref-api}

Previously, React provided two ways of managing refs: the legacy string ref API and the callback API. Although the string ref API was the more convenient of the two, it had [several downsides](https://github.com/facebook/react/issues/1373) and so our official recommendation was to use the callback form instead.
Anteriormente, o React fornecia duas maneiras de gerenciar refs: a legada API de string ref e a API de callback. Embora a API de string ref ter sido a mais conveniente das duas, ela tinha [várias desvantagens](https://github.com/facebook/react/issues/1373) e assim nossa recomendação oficial era usar a forma de callback.

Version 16.3 adds a new option for managing refs that offers the convenience of a string ref without any of the downsides:
A versão 16.3 adiciona uma nova opção para gerenciar refs que oferecem o conforto de uma string ref sem nenhuma das desvantagens:
`embed:16-3-release-blog-post/create-ref-example.js`

> **Note:**
> **Nota:**
>
> Callback refs will continue to be supported in addition to the new `createRef` API.
> As refs de callbacks continuarão sendo suportadas, além da nova API `createRef`.
>
> You don't need to replace callback refs in your components. They are slightly more flexible, so they will remain as an advanced feature.
> Você não precisa substituir as callback refs em seus componentes. Elas são um pouco mais flexíveis, portanto, elas permanecerão como um recurso avançado.

[Learn more about the new `createRef` API here.](/docs/refs-and-the-dom.html)
[Saiba mais sobre a nova API `createRef` aqui.](/docs/refs-and-the-dom.html)

## `forwardRef` API {#forwardref-api}
## API `forwardRef` {#forwardref-api}

Generally, React components are declarative, but sometimes imperative access to the component instances and the underlying DOM nodes is necessary. This is common for use cases like managing focus, selection, or animations. React provides [refs](/docs/refs-and-the-dom.html) as a way to solve this problem. However, component encapsulation poses some challenges with refs.
Geralmente, os componentes React são declarativos, mas às vezes é necessário o acesso imperativo às instâncias do componente e aos nós DOM necessários. Isso é comum em casos de uso, como gerenciamento de foco, seleção ou animações. O React fornece [refs](/docs/refs-and-the-dom.html) uma maneira de resolver este problema. No entanto, o encapsulamento de componentes apresenta alguns desafios com as refs.

For example, if you replace a `<button>` with a custom `<FancyButton>` component, the `ref` attribute on it will start pointing at the wrapper component instead of the DOM node (and would be `null` for function components). While this is desirable for "application-level" components like `FeedStory` or `Comment` that need to be encapsulated, it can be annoying for "leaf" components such as `FancyButton` or `MyTextInput` that are typically used like their DOM counterparts, and might need to expose their DOM nodes.
Por exemplo, se você trocar um `<button>` por um componente `<FancyButton>`, o atributo `ref` nele começará a apontar para o componente encapsulando em vez do nó DOM (e seria `null` para componentes funcionais). Embora isso seja desejável para componentes de "nível de aplicação" como `FeedStory` ou `Comment` que precisam ser encapsulados, isso pode ser incômodo para componentes "folha" como `FancyButton` ou `MyTextInput` que são tipicamente usados como seus equivalentes do DOM e podem precisar expor seus nós do DOM.

Ref forwarding is a new opt-in feature that lets some components take a `ref` they receive, and pass it further down (in other words, "forward" it) to a child. In the example below, `FancyButton` forwards its ref to a DOM `button` that it renders:
A referência de encaminhamento é um novo recurso de inclusão que permite que alguns componentes `ref` sejam recebidos, e passem para baixo (em outras palavras, "encaminhá-lo") para um filho. No exemplo abaixo, `FancyButton` encaminha seu ref para um `button` do DOM que renderiza:

`embed:16-3-release-blog-post/fancy-button-example.js`

This way, components using `FancyButton` can get a ref to the underlying `button` DOM node and access it if necessary—just like if they used a DOM `button` directly.
Dessa forma, os componentes que usam `FancyButton` podem obter uma ref ao nó inerente do `button` do DOM e acessá-lo se necessário for, como se usassem um `button` do DOM diretamente.

Ref forwarding is not limited to "leaf" components that render DOM nodes. If you write [higher order components](/docs/higher-order-components.html), we recommend using ref forwarding to automatically pass the ref down to the wrapped class component instances.
O encaminhamento de ref não está limitado para componentes de "folha" que rederizam nós do DOM. Se você escreve [componente de alta-ordem](/docs/higher-order-components.html), recomendamos o uso do encaminhamento de referência para passar automaticamente as ref para as instâncias do componente de classe wrapper.
thalees marked this conversation as resolved.
Show resolved Hide resolved

[Learn more about the forwardRef API here.](/docs/forwarding-refs.html)
[Saiba mais sobre a API forwardRef aqui.](/docs/forwarding-refs.html)

## Component Lifecycle Changes {#component-lifecycle-changes}
## Mudanças no Ciclo de Vida do Componente {#component-lifecycle-changes}

React's class component API has been around for years with little change. However, as we add support for more advanced features (such as [error boundaries](/docs/react-component.html#componentdidcatch) and the upcoming [async rendering mode](/blog/2018/03/01/sneak-peek-beyond-react-16.html)) we stretch this model in ways that it was not originally intended.
A API de componente de classe do React existe há anos com poucas mudanças. No entanto, como nós adicionamos suporte a recursos mais avançados (tal como [limite de erros](/docs/react-component.html#componentdidcatch) e o próximo [modo de renderização assíncrona](/blog/2018/03/01/sneak-peek-beyond-react-16.html)) nós estendemos esta API de maneiras que não foram originalmente projetadas.

For example, with the current API, it is too easy to block the initial render with non-essential logic. In part this is because there are too many ways to accomplish a given task, and it can be unclear which is best. We've observed that the interrupting behavior of error handling is often not taken into consideration and can result in memory leaks (something that will also impact the upcoming async rendering mode). The current class component API also complicates other efforts, like our work on [prototyping a React compiler](https://twitter.com/trueadm/status/944908776896978946).
Por exemplo, com a API atual, é muito fácil bloquear a renderização inicial com lógica não essencial. Em parte, isso ocorre porque há muitas maneiras de realizar uma determinada tarefa, e pode não ser claro qual é a melhor. Observamos que o comportamento de interrupção do tratamento de erros geralmente não é levado em consideração e pode resultar em vazamentos de memória (algo que também afetará o próximo modo de renderização assíncrona). A API do componente de classe atual também complica outros esforços, como o nosso trabalho em [prototipar um compilador React](https://twitter.com/trueadm/status/944908776896978946).

Many of these issues are exacerbated by a subset of the component lifecycles (`componentWillMount`, `componentWillReceiveProps`, and `componentWillUpdate`). These also happen to be the lifecycles that cause the most confusion within the React community. For these reasons, we are going to deprecate those methods in favor of better alternatives.
Muitos desses problemas são exacerbados por um subconjunto dos ciclos de vida dos componentes (`componentWillMount`, `componentWillReceiveProps`, e `componentWillUpdate`). Esses também são os ciclos de vida que mais causam confusão na comunidade React. Por essas razões, vamos depreciar esses métodos em favor de alternativas melhores.

We recognize that this change will impact many existing components. Because of this, the migration path will be as gradual as possible, and will provide escape hatches. (At Facebook, we maintain more than 50,000 React components. We depend on a gradual release cycle too!)
Reconhecemos que essa alteração afetará muitos componentes existentes. Por isso, o caminho de migração será o mais gradual possível e fornecerá alternativas de escape. (No Facebook, mantemos mais de 50.000 componentes React. Também dependemos de um ciclo de lançamento gradual!)

> **Note:**
> **Nota:**
>
> Deprecation warnings will be enabled with a future 16.x release, **but the legacy lifecycles will continue to work until version 17**.
> Os avisos de deprecação serão ativados com uma versão 16.x futura, **mas os ciclos de vida herdados continuarão funcionando até a versão 17**.
>
> Even in version 17, it will still be possible to use them, but they will be aliased with an "UNSAFE_" prefix to indicate that they might cause issues. We have also prepared an [automated script to rename them](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) in existing code.
> Mesmo na versão 17, ainda será possível usá-los, mas eles terão um prefixo "UNSAFE_" para indicar que podem causar problemas. Nós também preparamos um [script automatizado para renomeá-los](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) no código existente.

In addition to deprecating unsafe lifecycles, we are also adding a couple of new lifecyles:
* [`getDerivedStateFromProps`](/docs/react-component.html#static-getderivedstatefromprops) is being added as a safer alternative to the legacy `componentWillReceiveProps`. (Note that [in most cases you don't need either of them](/blog/2018/06/07/you-probably-dont-need-derived-state.html).)
* [`getSnapshotBeforeUpdate`](/docs/react-component.html#getsnapshotbeforeupdate) is being added to support safely reading properties from e.g. the DOM before updates are made.
Além de depreciar ciclos de vida inseguros, também estamos adicionando alguns novos ciclos de vida:
* [`getDerivedStateFromProps`](/docs/react-component.html#static-getderivedstatefromprops) está sendo adicionado como uma alternativa mais segura ao legado `componentWillReceiveProps`. (Note que [na maioria dos casos você não precisa de nenhum deles](/blog/2018/06/07/you-probably-dont-need-derived-state.html).)
* [`getSnapshotBeforeUpdate`](/docs/react-component.html#getsnapshotbeforeupdate) está sendo adicionado para oferecer suporte para leitura segura das propriedades, por exemplo, do DOM, antes que as atualizações sejam feitas.

[Learn more about these lifecycle changes here.](/blog/2018/03/27/update-on-async-rendering.html)
[Saiba mais sobre essas mudanças no ciclo de vida aqui.](/blog/2018/03/27/update-on-async-rendering.html)

## `StrictMode` Component {#strictmode-component}
## Componente `StrictMode` {#strictmode-component}

`StrictMode` is a tool for highlighting potential problems in an application. Like `Fragment`, `StrictMode` does not render any visible UI. It activates additional checks and warnings for its descendants.
`StrictMode` é uma ferramenta para destacar possíveis problemas em um aplicativo. Como o `Fragment`, o` StrictMode` não renderiza nenhuma UI visível. Ele ativa verificações e avisos adicionais para seus descendentes.

> **Note:**
> **Nota:**
>
> `StrictMode` checks are run in development mode only; _they do not impact the production build_.
> `StrictMode` as verificações são executadas apenas no modo de desenvolvimento; _eles não afetam a estrutura de produção_.

Although it is not possible for strict mode to catch all problems (e.g. certain types of mutation), it can help with many. If you see warnings in strict mode, those things will likely cause bugs for async rendering.
Embora não seja possível para o "strict mode" detectar todos os problemas (por exemplo, certos tipos de mutação), ele pode ajudar em muitos. Se você ver avisos no "strict mode", essas coisas provavelmente causarão bugs para renderização assíncrona.

In version 16.3, `StrictMode` helps with:
* Identifying components with unsafe lifecycles
* Warning about legacy string ref API usage
* Detecting unexpected side effects
Na versão 16.3, o `StrictMode` ajuda:
* Identificando componentes com ciclos de vida inseguros
* Aviso sobre o uso de string legada da API ref
* Detectando efeitos colaterais inesperados

Additional functionality will be added with future releases of React.
Funcionalidades adicionais serão adicionadas com versões futuras do React.

[Learn more about the `StrictMode` component here.](/docs/strict-mode.html)
[Aprenda mais sobre o componente `StrictMode` aqui.](/docs/strict-mode.html)