Skip to content

feat: translate docs Reconciliation page #193

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

Merged
merged 3 commits into from
Sep 16, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 42 additions & 42 deletions content/docs/reconciliation.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,32 @@ title: Reconciliation
permalink: docs/reconciliation.html
---

React provides a declarative API so that you don't have to worry about exactly what changes on every update. This makes writing applications a lot easier, but it might not be obvious how this is implemented within React. This article explains the choices we made in React's "diffing" algorithm so that component updates are predictable while being fast enough for high-performance apps.
React cung cấp một API tự động xác định những nơi bị thay đổi sau những lần cập nhật. Điều này làm cho việc viết ứng dụng trở nên dễ dàng hơn rất nhiều, nhưng có thể bạn muốn tìm hiểu thêm về cách React xác định những thay đổi trong DOM như thế nào. Bài viết này sẽ giải thích cách mà React đã thực hiện trong thuật toán "diffing" để đưa ra quyết định cập nhật components của bạn một cách có kiểm soát và đảm bảo performance (hiệu năng) của ứng dụng.

## Motivation {#motivation}

When you use React, at a single point in time you can think of the `render()` function as creating a tree of React elements. On the next state or props update, that `render()` function will return a different tree of React elements. React then needs to figure out how to efficiently update the UI to match the most recent tree.
Khi bạn sử dụng React, tại một thời điểm nào đó, bạn có nhận ra function (hàm) `render()` giống như việc tạo một tree (cây) các React element. Trong lần cập nhật state hoặc props tiếp theo, function `render()` đó sẽ trả về một tree các React element khác. Sau đó, React cần tìm ra cách cập nhật UI (giao diện người dùng) một cách hiệu quả để phù hợp với tree gần đây nhất.

There are some generic solutions to this algorithmic problem of generating the minimum number of operations to transform one tree into another. However, the [state of the art algorithms](https://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf) have a complexity in the order of O(n<sup>3</sup>) where n is the number of elements in the tree.
Có một số giải pháp chung cho vấn đề algorithmic (thuật toán) này là tạo ra số lượng phép toán tối thiểu để biến đổi một tree này thành một tree khác. Tuy nhiên, [state of the art algorithms (các thuật toán hiện đại)](https://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf) có độ phức tạp theo thứ tự là O(n<sup>3</sup>) trong đó n là số phần tử trong tree.

If we used this in React, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:
Nếu chúng tôi sử dụng điều này trong React, việc hiển thị 1000 phần tử sẽ yêu cầu cần phải chạy lên đến một tỷ phép so sánh. Đó quả là một sự trả giá quá đắt. Thay vào đó, React triển khai thuật toán heuristic O(n) dựa trên hai giả định:

1. Two elements of different types will produce different trees.
2. The developer can hint at which child elements may be stable across different renders with a `key` prop.
1. Hai element khác loại nhau sẽ tạo ra các tree khác nhau.
2. Developer có thể gợi ý tại các child element để có thể ổn định trên các hiển thị khác nhau bằng một `key` prop.

In practice, these assumptions are valid for almost all practical use cases.
Trong thực tế, những giả định này có giá trị đối với hầu hết các trường hợp sử dụng thực tế.

## The Diffing Algorithm {#the-diffing-algorithm}

When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.
Khi hai tree khác nhau, React đầu tiên sẽ so sánh hai root element. Hành vi khác nhau tùy thuộc vào loại của các root element.

### Elements Of Different Types {#elements-of-different-types}
### Elements Of Different Types (Khác loại) {#elements-of-different-types}

Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Going from `<a>` to `<img>`, or from `<Article>` to `<Comment>`, or from `<Button>` to `<div>` - any of those will lead to a full rebuild.
Bất cứ khi nào các root element có nhiều loại khác nhau, React sẽ phá bỏ tree cũ và xây dựng tree mới từ đầu. Đi từ `<a>` đến `<img>`, hoặc từ `<Article>` đến `<Comment>`, hoặc từ `<Button>` đến `<div>` - bất kỳ điều gì trong số đó sẽ dẫn đến việc xây dựng lại toàn bộ.

When tearing down a tree, old DOM nodes are destroyed. Component instances receive `componentWillUnmount()`. When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive `UNSAFE_componentWillMount()` and then `componentDidMount()`. Any state associated with the old tree is lost.
Khi phá bỏ một tree, các DOM node cũ sẽ bị destroy (phá hủy). Component instances nhận `componentWillUnmount()`. Khi xây dựng một tree mới, các DOM node mới sẽ được chèn vào DOM. Component instances nhận `UNSAFE_componentWillMount()` và sau đó là `componentDidMount()`. Bất kỳ state nào gắn với tree cũ đều sẽ bị mất đi.

Any components below the root will also get unmounted and have their state destroyed. For example, when diffing:
Bất kỳ component nào bên dưới root cũng sẽ bị unmounted (ngắt kết nối) và state của chúng sẽ bị destroy. Ví dụ, khi diffing:

```xml
<div>
Expand All @@ -41,56 +41,56 @@ Any components below the root will also get unmounted and have their state destr
</span>
```

This will destroy the old `Counter` and remount a new one.
Thao tác này sẽ destroy `Counter` cũ và remount (gắn lại) một `Counter` mới.

>Note:
>Ghi chú:
>
>These methods are considered legacy and you should [avoid them](/blog/2018/03/27/update-on-async-rendering.html) in new code:
>Các method này được coi là legacy (đã lỗi thời) và bạn nên [tránh chúng](/blog/2018/03/27/update-on-async-rendering.html) trong code mới:
>
>- `UNSAFE_componentWillMount()`

### DOM Elements Of The Same Type {#dom-elements-of-the-same-type}
### DOM Elements Of The Same Type (Cùng loại) {#dom-elements-of-the-same-type}

When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes. For example:
Khi so sánh hai React DOM element cùng loại, React sẽ xem xét các attribute (thuộc tính) của cả hai, giữ cùng một DOM node cơ bản và chỉ cập nhật các attribute đã thay đổi. Ví dụ:

```xml
<div className="before" title="stuff" />

<div className="after" title="stuff" />
```

By comparing these two elements, React knows to only modify the `className` on the underlying DOM node.
Bằng cách so sánh hai element này, React biết chỉ sửa đổi `className` trên DOM node bên dưới.

When updating `style`, React also knows to update only the properties that changed. For example:
Khi cập nhật `style`, React cũng chỉ cập nhật các property (thuộc tính) đã thay đổi. Ví dụ:

```xml
<div style={{color: 'red', fontWeight: 'bold'}} />

<div style={{color: 'green', fontWeight: 'bold'}} />
```

When converting between these two elements, React knows to only modify the `color` style, not the `fontWeight`.
Khi chuyển đổi giữa hai element này, React biết chỉ sửa đổi `color` màu chứ không phải `fontWeight`.

After handling the DOM node, React then recurses on the children.
Sau khi xử lý DOM node, React sau đó sẽ lặp lại trên các children (phần tử con).

### Component Elements Of The Same Type {#component-elements-of-the-same-type}

When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, and calls `UNSAFE_componentWillReceiveProps()`, `UNSAFE_componentWillUpdate()` and `componentDidUpdate()` on the underlying instance.
Khi một component được cập nhật, trường hợp vẫn như cũ, thì state đó được duy trì qua các lần render (hiển thị). React cập nhật các prop của các component instance bên dưới để khớp với element mới và gọi `UNSAFE_componentWillReceiveProps()`, `UNSAFE_componentWillUpdate()` `componentDidUpdate()` trên cá thể bên dưới.

Next, the `render()` method is called and the diff algorithm recurses on the previous result and the new result.
Tiếp theo, `render()` method được gọi và thuật toán diff lặp lại trên kết quả trước đó và kết quả mới.

>Note:
>Ghi chú:
>
>These methods are considered legacy and you should [avoid them](/blog/2018/03/27/update-on-async-rendering.html) in new code:
>Các method này được coi là legacy (đã lỗi thời) và bạn nên [tránh chúng](/blog/2018/03/27/update-on-async-rendering.html) trong code mới:
>
>- `UNSAFE_componentWillUpdate()`
>- `UNSAFE_componentWillReceiveProps()`

### Recursing On Children {#recursing-on-children}

By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there's a difference.
Theo mặc định, khi recursing (đệ quy) trên các children của một DOM node, React chỉ lặp lại trên cả hai danh sách children cùng một lúc và tạo ra một sự biến đổi bất cứ khi nào thấy sự khác biệt.

For example, when adding an element at the end of the children, converting between these two trees works well:
Ví dụ: khi thêm một element vào cuối phần tử children, việc chuyển đổi giữa hai tree này hoạt động tốt:

```xml
<ul>
Expand All @@ -105,9 +105,9 @@ For example, when adding an element at the end of the children, converting betwe
</ul>
```

React will match the two `<li>first</li>` trees, match the two `<li>second</li>` trees, and then insert the `<li>third</li>` tree.
React sẽ so sánh và thấy khớp giữa hai tree `<li>first</li>`, tương tự hai tree `<li>second</li>` và sau đó chèn tree `<li>third</li>`.

If you implement it naively, inserting an element at the beginning has worse performance. For example, converting between these two trees works poorly:
Nếu bạn triển khai nó một cách ngây thơ, đơn thuần thì việc chèn một element vào đầu sẽ có thể gây ra hiệu suất kém hơn. Ví dụ: chuyển đổi giữa hai tree này đang hoạt động kém:

```xml
<ul>
Expand All @@ -122,11 +122,11 @@ If you implement it naively, inserting an element at the beginning has worse per
</ul>
```

React will mutate every child instead of realizing it can keep the `<li>Duke</li>` and `<li>Villanova</li>` subtrees intact. This inefficiency can be a problem.
React sẽ thay đổi mọi child thay vì nhận ra rằng nó có thể giữ nguyên các subtree `<li>Duke</li>` `<li>Villanova</li>`. Sự kém hiệu quả này có thể là một vấn đề.

### Keys {#keys}

In order to solve this issue, React supports a `key` attribute. When children have keys, React uses the key to match children in the original tree with children in the subsequent tree. For example, adding a `key` to our inefficient example above can make the tree conversion efficient:
Để giải quyết vấn đề này, React hỗ trợ một `key` attribute. Khi children có key, React sử dụng key để ghép những children ở tree ban đầu với những children ở tree tiếp theo. Ví dụ: thêm một `key` vào từ ví dụ kém hiệu quả của chúng tôi ở trên có thể làm cho việc chuyển đổi tree trở nên có hiệu quả hơn:

```xml
<ul>
Expand All @@ -141,30 +141,30 @@ In order to solve this issue, React supports a `key` attribute. When children ha
</ul>
```

Now React knows that the element with key `'2014'` is the new one, and the elements with the keys `'2015'` and `'2016'` have just moved.
Bây giờ React biết rằng element key `'2014'` là element mới và các element có key `'2015'` `'2016'` vừa mới di chuyển.

In practice, finding a key is usually not hard. The element you are going to display may already have a unique ID, so the key can just come from your data:
Trong thực tế, việc tìm một key thường không khó. Element bạn sắp hiển thị có thể đã có một ID duy nhất, vì vậy, key có thể đến từ data (dữ liệu) của bạn:

```js
<li key={item.id}>{item.name}</li>
```

When that's not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. The key only has to be unique among its siblings, not globally unique.
Khi không phải như vậy, bạn có thể thêm property ID mới vào model của mình hoặc dùng cách băm một số phần nội dung để tạo key. Key phải là duy nhất trong số các element đồng cấp của nó, tuy nhiên nó không yêu cầu phải là duy nhất trên global.

As a last resort, you can pass an item's index in the array as a key. This can work well if the items are never reordered, but reorders will be slow.
Phương án cuối cùng, bạn có dùng index của một item trong array (mảng) làm key. Điều này có thể hoạt động tốt nếu các mục không bao giờ được sắp xếp lại, nhưng nếu phải sắp xếp lại thì sẽ rất chậm.

Reorders can also cause issues with component state when indexes are used as keys. Component instances are updated and reused based on their key. If the key is an index, moving an item changes it. As a result, component state for things like uncontrolled inputs can get mixed up and updated in unexpected ways.
Việc sắp xếp lại cũng có thể gây ra sự cố với component state khi các index được sử dụng làm key. Các component instance được cập nhật và sử dụng lại dựa trên key của chúng. Nếu key là một index, việc di chuyển một item sẽ thay đổi nó. Do đó, component state cho những thứ như input không được kiểm soát có thể bị trộn lẫn và cập nhật theo những cách không mong muốn.

Here is [an example of the issues that can be caused by using indexes as keys](codepen://reconciliation/index-used-as-key) on CodePen, and here is [an updated version of the same example showing how not using indexes as keys will fix these reordering, sorting, and prepending issues](codepen://reconciliation/no-index-used-as-key).
Dưới đây là [ví dụ về các sự cố có thể gây ra khi sử dụng index làm key](codepen://reconciliation/index-used-as-key) trên CodePen và đây là [phiên bản cập nhật của cùng một ví dụ cho thấy cách không sử dụng index làm key sẽ khắc phục các vấn đề reordering, sorting prepending](codepen://reconciliation/no-index-used-as-key).

## Tradeoffs {#tradeoffs}

It is important to remember that the reconciliation algorithm is an implementation detail. React could rerender the whole app on every action; the end result would be the same. Just to be clear, rerender in this context means calling `render` for all components, it doesn't mean React will unmount and remount them. It will only apply the differences following the rules stated in the previous sections.
Điều quan trọng cần nhớ là reconciliation algorithm là một implementation detail. React có thể rerender toàn bộ ứng dụng trên mọi action; kết quả cuối cùng sẽ giống nhau. Nói dễ hiểu hơn, rerender trong ngữ cảnh này có nghĩa là gọi `render` cho tất cả các component, nó không có nghĩa là React sẽ unmount (ngắt kết nối) và remount (gắn kết lại) chúng. Nó sẽ chỉ áp dụng những điểm khác biệt theo các quy tắc đã nêu trong các phần trước.

We are regularly refining the heuristics in order to make common use cases faster. In the current implementation, you can express the fact that a subtree has been moved amongst its siblings, but you cannot tell that it has moved somewhere else. The algorithm will rerender that full subtree.
Chúng tôi thường xuyên tinh chỉnh phương pháp phỏng đoán để làm cho các trường hợp sử dụng phổ biến nhanh hơn. Trong triển khai hiện tại, trên thực tế bạn có thể thấy rằng một subtree đã được di chuyển giữa các anh chị em của nó, nhưng bạn không thể nói rằng nó đã di chuyển đến một nơi khác. Thuật toán sẽ rerender đầy đủ subtree đó.

Because React relies on heuristics, if the assumptions behind them are not met, performance will suffer.
Bởi vì React dựa trên heuristics, nếu các giả định đằng sau chúng không được đáp ứng, hiệu suất sẽ bị ảnh hưởng.

1. The algorithm will not try to match subtrees of different component types. If you see yourself alternating between two component types with very similar output, you may want to make it the same type. In practice, we haven't found this to be an issue.
1. Algorithm sẽ không cố gắng so khớp các subtree của các loại component khác nhau. Nếu bạn thấy mình xen kẽ giữa hai loại component có output rất giống nhau, bạn có thể muốn đặt nó cùng một loại. Trong thực tế, chúng tôi không thấy đây là một vấn đề.

2. Keys should be stable, predictable, and unique. Unstable keys (like those produced by `Math.random()`) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
2. Các key phải ổn định, dễ đoán và duy nhất. Các key không ổn định (như key được tạo bởi `Math.random()`) sẽ khiến nhiều phiên bản component và DOM node được tạo lại một cách không cần thiết, điều này có thể gây suy giảm hiệu suất và mất state bên trong các child component.