Home javascript Why is Key in React need only in the listings?

Why is Key in React need only in the listings?

Author

Date

Category

The task was set to implement its JSX Factory. From the React documentation, we know that JSX is transplanted to call the React.CreateEelement function (Type, Props, Child) , where child is expressed by the REST parameter (transmits an array of descendants through the comma). But how can the current and new tree compare? After all, these are absolutely separate objects.

import react, {component} from 'react';
Class App Extends Component {
 render () {
  Return (
   & lt; div & gt;
    & lt; p & gt; it's & lt; / p & gt;
    & lt; p & gt; ok & lt; / p & gt;
   & lt; / div & gt;
  );
 }
}
EXPORT DEFAULT APP;

In addition, what is the criterion for the impossibility of partial rendering without the KEY field in the listing? We can put two blocks block in a row and nothing terrible will not happen …


Answer 1, Authority 100%

When receiving Child occurs “Massiflash” – to get rid of inclusions map () , which return an array. Next, the comparison of the elements of the tree can be carried out by the following algorithm:

  1. We compare Key and Type current associated elements
  2. If they coincided, go to parents

    • if they coincided, repeat the action
    • if one of the parents did not turn out, the elements are not equal to
    • If there were no two parents at once, the comparison is true

Implementation of this algorithm in pseudo code:

bool element :: equals (
  Const Element * A,
  Const element * b,
  BOOL RECURSIVE = TRUE
) {
  If (A- & GT; Key! = B- & GT; KEY) {
    RETURN FALSE;
  } ELSE If (A- & GT; Type! = B- & GT; TYPE) {
    RETURN FALSE;
  } ELSE if (recursive) {
    Const element * parent1 = a;
    const element * parent2 = b;
    While (True) {
      Parent1 = Parent1- & gt; parent;
      Parent2 = Parent2- & gt; parent;
      if (parent1 == nullptr & amp; & amp; parent2 == nullptr) {
        RETURN TRUE;
      } ELSE if (parent1 == nullptr & amp; & amp; parent2! = nullptr) {
        RETURN FALSE;
      } ELSE If (Parent1! = nullptr & amp; & amp; parent2 == nullptr) {
        RETURN FALSE;
      } ELSE If (! Equals (Parent1, Parent2, False)) {
        RETURN FALSE;
      } else {
        Continue;
      }
    }
  } else {
    RETURN TRUE;
  }
}

The criterion for the impossibility of partial rendering is the presence of three or more (in the string representation of the tree of descendants) of equivalent elements in a row, since when trying to determine the changes will be removed by the latter, and not changed.

In more detail about this phenomenon, you can read in this Repositories.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions