You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/blog/2016-01-08-A-implies-B-does-not-imply-B-implies-A.md
+14-18Lines changed: 14 additions & 18 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,15 +3,14 @@ title: "(A => B) !=> (B => A)"
3
3
author: [jimfb]
4
4
---
5
5
6
-
The documentation for`componentWillReceiveProps`states that`componentWillReceiveProps`will be invoked when the props change as the result of a rerender. Some people assume this means "if`componentWillReceiveProps`is called, then the props must have changed", but that conclusion is logically incorrect.
6
+
A documentação para`componentWillReceiveProps`diz que`componentWillReceiveProps`será invocado quando as props mudam como resultado de uma re-renderização. Algumas pessoas assumem que isso significa "se`componentWillReceiveProps`é chamado, então as props devem ter mudado", mas essa conclusão é logicamente incorreta.
7
7
8
-
The guiding principle is one of my favorites from formal logic/mathematics:
9
-
> A implies B does not imply B implies A
8
+
O princípio orientador é um dos meus favoritos da lógica/matemática formal:
9
+
> A implica B não implica B implica A
10
10
11
-
Example: "If I eat moldy food, then I will get sick" does not imply "if I am sick, then I must have eaten moldy food". There are many other reasons I could be feeling sick. For instance, maybe the flu is circulating around the office. Similarly, there are many reasons that `componentWillReceiveProps` might get called, even if the props didn’t change.
12
-
13
-
If you don’t believe me, call `ReactDOM.render()` three times with the exact same props, and try to predict the number of times `componentWillReceiveProps` will get called:
11
+
Exemplo: "Se eu comer comida mofada, eu ficarei doente" não implica "se estou doente, então eu devo ter comido comida mofada". Existem muitas outras razões pelas quais eu poderia estar me sentindo doente. Por exemplo, a gripe tem circulado no escritório. Da mesma forma, existem várias razões para que `componentWillReceiveProps` seja chamado, mesmo que as props não tenham mudado.
14
12
13
+
Se você não acredita em mim, chame `ReactDOM.render()` três vezes com exatamente as mesmas props, e tente prever o número de vezes que `componentWillReceiveProps` será chamado:
Neste caso, a resposta é "2". React chama `componentWillReceiveProps` duas vezes (uma vez para cada um dos dois updates). Nas duas vezes, o valor "drinks" é impresso (isto é, as props não mudaram).
34
34
35
-
In this case, the answer is "2". React calls `componentWillReceiveProps` twice (once for each of the two updates). Both times, the value of "drinks" is printed (ie. the props didn’t change).
36
-
37
-
To understand why, we need to think about what *could* have happened. The data *could* have changed between the initial render and the two subsequent updates, if the code had performed a mutation like this:
35
+
Para entender o porquê, precisamos pensar no que *poderia* ter acontecido. Os dados *poderiam* ter mudado entre a renderização inicial e as duas atualizações subsequentes, se o código tivesse realizado uma mutação como essa:
React has no way of knowing that the data didn’t change. Therefore, React needs to call `componentWillReceiveProps`, because the component needs to be notified of the new props (even if the new props happen to be the same as the old props).
49
-
50
-
You might think that React could just use smarter checks for equality, but there are some issues with this idea:
51
-
52
-
* The old `mydata` and the new `mydata` are actually the same physical object (only the object’s internal value changed). Since the references are triple-equals-equal, doing an equality check doesn’t tell us if the value has changed. The only possible solution would be to have created a deep copy of the data, and then later do a deep comparison - but this can be prohibitively expensive for large data structures (especially ones with cycles).
53
-
* The `mydata` object might contain references to functions which have captured variables within closures. There is no way for React to peek into these closures, and thus no way for React to copy them and/or verify equality.
54
-
* The `mydata` object might contain references to objects which are re-instantiated during the parent's render (ie. not triple-equals-equal) but are conceptually equal (ie. same keys and same values). A deep-compare (expensive) could detect this, except that functions present a problem again because there is no reliable way to compare two functions to see if they are semantically equivalent.
46
+
React não tem como saber que os dados não foram alterados. Portanto, React precisa chamar `componentWillReceiveProps`, porque o componente precisa ser notificado sobre as novas props (mesmo se as novas props forem iguais as props antigas).
55
47
56
-
Given the language constraints, it is sometimes impossible for us to achieve meaningful equality semantics. In such cases, React will call `componentWillReceiveProps` (even though the props might not have changed) so the component has an opportunity to examine the new props and act accordingly.
48
+
Você pode pensar que o React poderia apenas usar verificações mais inteligentes para igualidade, mas há alguns problemas com essa ideia:
57
49
58
-
As a result, your implementation of `componentWillReceiveProps` MUST NOT assume that your props have changed. If you want an operation (such as a network request) to occur only when props have changed, your `componentWillReceiveProps` code needs to check to see if the props actually changed.
50
+
* O antigo `mydata` e o novo `mydata` são na verdade o mesmo objeto físico (apenas o valor interno do objeto mudou). Como as referências são triplamente iguais, fazer uma verificação de igualdade não nos diz se o valor mudou. A única solução possível seria ter criado uma cópia profunda dos dados e, posteriormente, fazer uma comparação profunda - mas isso pode ser proibitivamente caro para grandes estruturas de dados (especialmente aquelas com ciclos).
51
+
* O objeto `mydata` pode conter referências para funções que capturaram variáveis dentro de clausuras. Não há como o React espiar dentro dessas clausuras e, portanto, não há como o React copiá-las e/ou verificar sua igualdade.
52
+
* O objeto `mydata` pode conter referências a objetos que são re-instanciados durante uma re-renderização do pai (ou seja, não são triplamente igual) mas são conceitualmente iguais (ou seja, mesmas chaves e mesmos valores). Uma comparação profunda (cara) poderia detectar isso, exceto que as funções apresentam um problema novamente porque não há uma forma confiável para comparar duas funções para verificar se elas são semanticamente equivalentes.
59
53
54
+
Dadas as restrições da linguagem, às vezes é impossível alcançarmos semânticas de igualdade significativas. Nesses casos, o React irá chamar `componentWillReceiveProps` (mesmo que as props não tenham mudado) para que o componente tenha a oportunidade de examinar as novas props e agir de acordo.
60
55
56
+
Como resultado, sua implementação do `componentWillReceiveProps` NÂO DEVE assumir que suas props foram alteradas. Se você deseja que uma operação (como uma solicitação de rede) ocorra apenas quando props foram alteradas, o código do `componentWillReceiveProps` precisa verificar se as props foram realmente alteradas.
title: "Descontinuando o Suporte ao IE 8 no React DOM"
3
3
author: [sophiebits]
4
4
---
5
5
6
-
Since its 2013 release, React has supported all popular browsers, including Internet Explorer 8 and above. We handle normalizing many quirks present in old browser versions, including event system differences, so that your app code doesn't have to worry about most browser bugs.
6
+
Desde seu lançamento em 2013, o React oferece suporte a todos os navegadores populares, incluindo o Internet Explorer 8 e superior. Lidamos com a normalização de muitas peculiaridades presentes nas versões antigas do navegador, incluindo diferenças no sistema de eventos, para que o código do seu aplicativo não precise se preocupar com a maioria dos erros do navegador.
7
7
8
-
Today, Microsoft [discontinued support for older versions of IE](https://www.microsoft.com/en-us/WindowsForBusiness/End-of-IE-support). Starting with React v15, we're discontinuing React DOM's support for IE8. We've heard that most ReactDOM apps already don't support old versions of Internet Explorer, so this shouldn't affect many people. This change will help us develop faster and make React DOM even better. (We won't actively remove IE 8–related code quite yet, but we will deprioritize new bugs that are reported. If you need to support IE 8 we recommend you stay on React v0.14.)
8
+
Hoje, a Microsoft [interrompeu o suporte para versões mais antigas do IE](https://www.microsoft.com/en-us/WindowsForBusiness/End-of-IE-support). A partir do React v15, descontinuamos o suporte do React DOM's para o IE8. Ouvimos dizer que a maioria dos aplicativos ReactDOM já não suporta versões antigas do Internet Explorer, portanto, isso não deve afetar muitas pessoas. Essa alteração nos ajudará a desenvolver mais rapidamente e tornar o React DOM ainda melhor. (Ainda não removeremos ativamente o código relacionado ao IE 8, mas nós iremos despriorizar novos bugs que sejam relatados. Se você precisar dar suporte ao IE 8 recomendamos que você permaneça no React v0.14.)
9
9
10
-
React DOM will continue to support IE 9 and above for the foreseeable future.
10
+
O React DOM continuará a oferecer suporte ao IE 9 e superior no futuro próximo.
0 commit comments