Czym jest ostrzeżenie ReactaJS: Each child in a list should have a unique „key” prop?

Czym jest ostrzeżenie ReactaJS: Each child in a list should have a unique „key” prop?

Czym jest ostrzeżenie ReactaJS: Each child in a list should have a unique „key” prop?

React wymaga aby każdy element listy posiadał unikalne ID. Dlatego poniższy kod:  

<div>
  { props.arrayOfElements.map(text => <p>{ text }</p>) }
</div>

wygeneruje ostrzeżenie w konsoli:

Warning: Each child in a list should have a unique "key" prop.

Check the render method of `Test`. See https://reactjs.org/link/warning-keys for more information

Rozwiązaniem problemu jest nadanie wspomnianych ID elementom listy:

{ props.arrayOfElements.map((text, index) => <p key = { index }>{ text }</p>) }

Inne z tej kategorii: Programowanie
Takie tam: www.marczuk.org

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *