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

Translated React v16.6.0: lazy, memo and contextType #179

Merged
merged 14 commits into from
Apr 10, 2019
Merged
98 changes: 49 additions & 49 deletions content/blog/2018-10-23-react-v-16-6.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
---
title: "React v16.6.0: lazy, memo and contextType"
title: "React v16.6.0: lazy, memo e contextType"
author: [sebmarkbage]
---

Today we're releasing React 16.6 with a few new convenient features. A form of PureComponent/shouldComponentUpdate for function components, a way to do code splitting using Suspense and an easier way to consume Context from class components.
Hoje estamos lançando o React 16.6 com alguns novos recursos convenientes. Uma forma de utilizar o PureComponent / shouldComponentUpdate para componentes de função, uma maneira de fazer a divisão de código usando Suspense e uma maneira mais fácil de consumir o Contexto de componentes de classe.

Check out the full [changelog](#changelog) below.
Confira o [changelog](#changelog) completo abaixo.

## [`React.memo`](/docs/react-api.html#reactmemo) {#reactmemo}

Class components can bail out from rendering when their input props are the same using [`PureComponent`](/docs/react-api.html#reactpurecomponent) or [`shouldComponentUpdate`](/docs/react-component.html#shouldcomponentupdate). Now you can do the same with function components by wrapping them in [`React.memo`](/docs/react-api.html#reactmemo).
Os componentes de classe podem não ser renderizados quando seus objetos de entrada são os mesmos usando [`PureComponent`](/docs/react-api.html#reactpurecomponent) ou [`shouldComponentUpdate`](/docs/react-component.html#shouldcomponentupdate). Agora você pode fazer o mesmo com componentes de função envolvendo-os [`React.memo`](/docs/react-api.html#reactmemo).

```js
const MyComponent = React.memo(function MyComponent(props) {
/* only rerenders if props change */
/* só re-renderiza se as prop forem alteradas */
});
```

## [`React.lazy`](/docs/code-splitting.html#reactlazy): Code-Splitting with `Suspense` {#reactlazy-code-splitting-with-suspense}
## [`React.lazy`](/docs/code-splitting.html#reactlazy): Divisão de código com `Suspense` {#reactlazy-code-splitting-with-suspense}

You may have seen [Dan's talk about React Suspense at JSConf Iceland](/blog/2018/03/01/sneak-peek-beyond-react-16.html). Now you can use the Suspense component to do [code-splitting](/docs/code-splitting.html#reactlazy) by wrapping a dynamic import in a call to `React.lazy()`.
Você pode ter visto a [talk do Dan sobre React Suspense na JSConf Iceland](/blog/2018/03/01/sneak-peek-beyond-react-16.html). Agora você pode usar o componente Suspense para fazer a [divisão de código](/docs/code-splitting.html#reactlazy) agrupando uma importação dinâmica em uma chamada `React.lazy()`.

```js
import React, {lazy, Suspense} from 'react';
Expand All @@ -34,26 +34,26 @@ function MyComponent() {
}
```

The Suspense component will also allow library authors to start building data fetching with Suspense support in the future.
O componente Suspense também permitirá que os autores da biblioteca iniciem a busca de dados com o suporte ao Suspense no futuro.

> Note: This feature is not yet available for server-side rendering. Suspense support will be added in a later release.
> Nota: Esse recurso ainda não está disponível para renderização no lado do servidor. O suporte para suspense será adicionado em uma versão posterior.

## [`static contextType`](/docs/context.html#classcontexttype) {#static-contexttype}

In [React 16.3](/blog/2018/03/29/react-v-16-3.html) we introduced the official Context API as a replacement to the previous [Legacy Context](/docs/legacy-context.html) API.
No [React 16.3](/blog/2018/03/29/react-v-16-3.html) introduzimos a API de Contexto oficial como uma substituição à API de [Context Legado](/docs/legacy-context.html).

```js
const MyContext = React.createContext();
```

We've heard feedback that adopting the new render prop API can be difficult in class components. So we've added a convenience API to [consume a context value from within a class component](/docs/context.html#classcontexttype).
Ouvimos comentários de que a adoção da nova API de suporte de renderização pode ser difícil em componentes de classe. Então, adicionamos uma conveniente API para [consumir um valor de contexto de dentro de um componente de classe](/docs/context.html#classcontexttype).

```js
class MyClass extends React.Component {
static contextType = MyContext;
componentDidMount() {
let value = this.context;
/* perform a side-effect at mount using the value of MyContext */
/* realizar um efeito colateral na montagem do componente usando o valor do MyContext */
}
componentDidUpdate() {
let value = this.context;
Expand All @@ -65,88 +65,88 @@ class MyClass extends React.Component {
}
render() {
let value = this.context;
/* render something based on the value of MyContext */
/* renderizando algo baseado no valor de MyContext */
}
}
```

## [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) {#static-getderivedstatefromerror}

React 16 introduced [Error Boundaries](/blog/2017/07/26/error-handling-in-react-16.html) for handling errors thrown in React renders. We already had the `componentDidCatch` lifecycle method which gets fired after an error has already happened. It's great for logging errors to the server. It also lets you show a different UI to the user by calling `setState`.
O React 16 introduziu [Error Boundaries](/blog/2017/07/26/error-handling-in-react-16.html) para gerenciar os erros lançados nas renderizações do React. Já tivemos o `componentDidCatch` um método de ciclo de vida que é acionado depois que um erro já aconteceu. É ótimo para registrar erros no servidor. Ele também permite mostrar uma interface do usuário diferente para o usuário, chamando `setState`.

Before that is fired, we render `null` in place of the tree that threw an error. This sometimes breaks parent components that don't expect their refs to be empty. It also doesn't work to recover from errors on the server since the `Did` lifecycle methods don't fire during server-side rendering.
Antes que seja disparado, processamos `null` no lugar da árvore que gerou um erro. Isso às vezes interrompe os componentes pai que não esperam que seus representantes estejam vazios. Ele também não funciona para se recuperar de erros no servidor, pois os ciclo de vida `Did` não são acionados durante a renderização no lado do servidor.

We're adding another error method that lets you render the fallback UI before the render completes. See the docs for [`getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror).
Estamos adicionando outro método de erro que permite renderizar a interface do usuário de fallback antes que a renderização seja concluída. Veja os documentos para [`getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror).

> Note: `getDerivedStateFromError()` is not yet available for server-side rendering. It is designed to work with server-side rendering in a future release. We're releasing it early so that you can start preparing to use it.
> Nota: `getDerivedStateFromError()` ainda não está disponível para renderização no lado do servidor. Ele será projetado para funcionar com a renderização do lado do servidor em uma versão futura. Estamos liberando isso cedo para que você possa começar a se preparar para usá-lo.

## Deprecations in StrictMode {#deprecations-in-strictmode}
## Depreciações no StrictMode {#deprecations-in-strictmode}

In [16.3](/blog/2018/03/29/react-v-16-3.html#strictmode-component) we introduced the [`StrictMode`](/docs/strict-mode.html) component. It lets you opt-in to early warnings for patterns that might cause problems in the future.
Na versão [16.3](/blog/2018/03/29/react-v-16-3.html#strictmode-component) introduzmos o componente [`StrictMode`](/docs/strict-mode.html). Ele permite que você aceite alertas antecipados quanto a padrões que possam causar problemas no futuro.

We've added two more APIs to the list of deprecated APIs in `StrictMode`. If you don't use `StrictMode` you don't have to worry; these warning won't fire for you.
Adicionamos mais duas API's na lista de depreciados no `StrictMode`. Se você não usa o `StrictMode` não precisa se preocupar pois esses avisos não serão disparados por você.

* __ReactDOM.findDOMNode()__ - This API is often misunderstood and most uses of it are unnecessary. It can also be surprisingly slow in React 16. [See the docs](/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) for possible upgrade paths.
* __Legacy Context__ using contextTypes and getChildContext - Legacy context makes React slightly slower and bigger than it needs to be. That's why we strongly want to encourage upgrading to the [new context API](/docs/context.html). Hopefully the addition of the [`contextType`](/docs/context.html#classcontexttype) API makes this a bit easier.
* __ReactDOM.findDOMNode()__ - Esta API normalmente é mal compreendida e a maioria dos usos dela é desnecessária. Também pode ser surpreendentemente lento no React 16. [Veja a documentação](/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) para possíveis atualizações.
* __Legacy Context__ usando contextTypes e getChildContext - Contexto legado torna o React um pouco mais lento e maior do que o necessário. É por isso que queremos incentivar a atualização para a [nova context API](/docs/context.html). Espero que a adição da [`contextType`](/docs/context.html#classcontexttype) API torne isso um pouco mais fácil.

If you're having trouble upgrading, we'd like to hear your feedback.
Se você está com problemas para fazer upgrade, gostaríamos de receber seus comentários.

## Installation {#installation}
## Instalação {#installation}

React v16.6.0 is available on the npm registry.
React v16.6.0 está disponível no npm.

To install React 16 with Yarn, run:
Para instalar o React 16 com Yarn, execute:

```bash
yarn add react@^16.6.0 react-dom@^16.6.0
```

To install React 16 with npm, run:
Para instalar o React 16 com npm, execute:

```bash
npm install --save react@^16.6.0 react-dom@^16.6.0
```

We also provide UMD builds of React via a CDN:
Nós também fornecemos compilações UMD de React via CDN:

```html
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
```

Refer to the documentation for [detailed installation instructions](/docs/installation.html).
Consulte a documentação para [instruções detalhadas de instalação](/docs/installation.html).

## Changelog {#changelog}

### React {#react}

* Add `React.memo()` as an alternative to `PureComponent` for functions. ([@acdlite](https://github.com/acdlite) in [#13748](https://github.com/facebook/react/pull/13748))
* Add `React.lazy()` for code splitting components. ([@acdlite](https://github.com/acdlite) in [#13885](https://github.com/facebook/react/pull/13885))
* `React.StrictMode` now warns about legacy context API. ([@bvaughn](https://github.com/bvaughn) in [#13760](https://github.com/facebook/react/pull/13760))
* `React.StrictMode` now warns about `findDOMNode`. ([@sebmarkbage](https://github.com/sebmarkbage) in [#13841](https://github.com/facebook/react/pull/13841))
* Rename `unstable_AsyncMode` to `unstable_ConcurrentMode`. ([@trueadm](https://github.com/trueadm) in [#13732](https://github.com/facebook/react/pull/13732))
* Rename `unstable_Placeholder` to `Suspense`, and `delayMs` to `maxDuration`. ([@gaearon](https://github.com/gaearon) in [#13799](https://github.com/facebook/react/pull/13799) and [@sebmarkbage](https://github.com/sebmarkbage) in [#13922](https://github.com/facebook/react/pull/13922))
* Adicione o `React.memo()` como uma alternativa `PureComponent` para funções. ([@acdlite](https://github.com/acdlite) em [#13748](https://github.com/facebook/react/pull/13748))
* Adicione o `React.lazy()` para componentes de divisão de código. ([@acdlite](https://github.com/acdlite) em [#13885](https://github.com/facebook/react/pull/13885))
* `React.StrictMode` agora avisa sobre a API de contexto legado. ([@bvaughn](https://github.com/bvaughn) em [#13760](https://github.com/facebook/react/pull/13760))
* `React.StrictMode` agora avisa sobre `findDOMNode`. ([@sebmarkbage](https://github.com/sebmarkbage) em [#13841](https://github.com/facebook/react/pull/13841))
* Renomeie `unstable_AsyncMode` para `unstable_ConcurrentMode`. ([@trueadm](https://github.com/trueadm) em [#13732](https://github.com/facebook/react/pull/13732))
* Renomeie `unstable_Placeholder` para `Suspense`, e `delayMs` para `maxDuration`. ([@gaearon](https://github.com/gaearon) em [#13799](https://github.com/facebook/react/pull/13799) e [@sebmarkbage](https://github.com/sebmarkbage) em [#13922](https://github.com/facebook/react/pull/13922))

### React DOM {#react-dom}

* Add `contextType` as a more ergonomic way to subscribe to context from a class. ([@bvaughn](https://github.com/bvaughn) in [#13728](https://github.com/facebook/react/pull/13728))
* Add `getDerivedStateFromError` lifecycle method for catching errors in a future asynchronous server-side renderer. ([@bvaughn](https://github.com/bvaughn) in [#13746](https://github.com/facebook/react/pull/13746))
* Warn when `<Context>` is used instead of `<Context.Consumer>`. ([@trueadm](https://github.com/trueadm) in [#13829](https://github.com/facebook/react/pull/13829))
* Fix gray overlay on iOS Safari. ([@philipp-spiess](https://github.com/philipp-spiess) in [#13778](https://github.com/facebook/react/pull/13778))
* Fix a bug caused by overwriting `window.event` in development. ([@sergei-startsev](https://github.com/sergei-startsev) in [#13697](https://github.com/facebook/react/pull/13697))
* Adicionado `contextType` como uma maneira mais ergonômica de se inscrever no contexto de uma classe. ([@bvaughn](https://github.com/bvaughn) em [#13728](https://github.com/facebook/react/pull/13728))
* Adicionado `getDerivedStateFromError` método de ciclo de vida para capturar erros futuros e assíncronos do lado do servidor. ([@bvaughn](https://github.com/bvaughn) em [#13746](https://github.com/facebook/react/pull/13746))
* Avisa quando `<Context>` é chamado ao invés de `<Context.Consumer>`. ([@trueadm](https://github.com/trueadm) em [#13829](https://github.com/facebook/react/pull/13829))
* Corrigido a sobreposição cinza no iOS Safari. ([@philipp-spiess](https://github.com/philipp-spiess) em [#13778](https://github.com/facebook/react/pull/13778))
* Corrigido um bug causado pela substituição `window.event` no desenvolvimento. ([@sergei-startsev](https://github.com/sergei-startsev) em [#13697](https://github.com/facebook/react/pull/13697))

### React DOM Server {#react-dom-server}

* Add support for `React.memo()`. ([@alexmckenley](https://github.com/alexmckenley) in [#13855](https://github.com/facebook/react/pull/13855))
* Add support for `contextType`. ([@alexmckenley](https://github.com/alexmckenley) and [@sebmarkbage](https://github.com/sebmarkbage) in [#13889](https://github.com/facebook/react/pull/13889))
* Adicionado suporte para `React.memo()`. ([@alexmckenley](https://github.com/alexmckenley) em [#13855](https://github.com/facebook/react/pull/13855))
* Adicionado suporte para `contextType`. ([@alexmckenley](https://github.com/alexmckenley) em [@sebmarkbage](https://github.com/sebmarkbage) em [#13889](https://github.com/facebook/react/pull/13889))

### Scheduler (Experimental) {#scheduler-experimental}

* Rename the package to `scheduler`. ([@gaearon](https://github.com/gaearon) in [#13683](https://github.com/facebook/react/pull/13683))
* Support priority levels, continuations, and wrapped callbacks. ([@acdlite](https://github.com/acdlite) in [#13720](https://github.com/facebook/react/pull/13720) and [#13842](https://github.com/facebook/react/pull/13842))
* Improve the fallback mechanism in non-DOM environments. ([@acdlite](https://github.com/acdlite) in [#13740](https://github.com/facebook/react/pull/13740))
* Schedule `requestAnimationFrame` earlier. ([@acdlite](https://github.com/acdlite) in [#13785](https://github.com/facebook/react/pull/13785))
* Fix the DOM detection to be more thorough. ([@trueadm](https://github.com/trueadm) in [#13731](https://github.com/facebook/react/pull/13731))
* Fix bugs with interaction tracing. ([@bvaughn](https://github.com/bvaughn) in [#13590](https://github.com/facebook/react/pull/13590))
* Add the `envify` transform to the package. ([@mridgway](https://github.com/mridgway) in [#13766](https://github.com/facebook/react/pull/13766))
* Renomeado o pacote para `scheduler`. ([@gaearon](https://github.com/gaearon) em [#13683](https://github.com/facebook/react/pull/13683))
* Suportar níveis de prioridade, continuações e retornos de chamada agrupados. ([@acdlite](https://github.com/acdlite) em [#13720](https://github.com/facebook/react/pull/13720) e [#13842](https://github.com/facebook/react/pull/13842))
* Melhorado o mecanismo de fallback em ambientes non-DOM ([@acdlite](https://github.com/acdlite) em [#13740](https://github.com/facebook/react/pull/13740))
* Agendado `requestAnimationFrame` antes. ([@acdlite](https://github.com/acdlite) em [#13785](https://github.com/facebook/react/pull/13785))
* Corrigido a detecção do DOM para ser mais completa. ([@trueadm](https://github.com/trueadm) em [#13731](https://github.com/facebook/react/pull/13731))
* Corrigir erros com o rastreamento de interação. Corrigir erros com o rastreamento de interação.([@bvaughn](https://github.com/bvaughn) em [#13590](https://github.com/facebook/react/pull/13590))
* Adicionado a transformação `envify` ao pacote. ([@mridgway](https://github.com/mridgway) em [#13766](https://github.com/facebook/react/pull/13766))