Implement key uniqueness on different elements

Is the following answer a unique key in React?

<span>
    {someArray.map(function (a, index) {
        return (
            <span key={index}>{a}</span>
        );
    })}
</span>

<span>
    {someArray2.map(function (a, index) {
        return (
                <span key={index}>{a}</span>
        );
    })}
</span>

In this case, both built- spanin loops will have the same key, but these are children of different parents. It's good?

+4
source share
2 answers

Yes, it is considered unique. React uses the keys in its conciliator to decide how to mutate the DOM in the most efficient way.

In general, problems that identify nodes in the same hierarchy (siblings) between renders are solved.

For example, if you have:

// render A
<div class='parent'>
  <div>one</div>
</div>

// render B
<div class='parent'>
  <div>two</div>
  <div>one</div>
</div>

, <div>one</div> , , , <div>two</div> . <div>one</div> , , , , , , <div>two</div> .

:

, ,

: https://facebook.imtqy.com/react/docs/reconciliation.html#keys

+6

, . , -.

: . , .

, React , , .

, , , .

:

 {someArray.map(function (element) {
   return (
     <span key={element.id}>{element.name}</span>
   );
 })}

:

{someArray.map(function (element, key) {
  return (
    <span key={key}>{element.name}</span>
  );
})}

docs :

. , , . , ID .

+1
source

All Articles