I\'m getting this warning:
Warning: Each child in an array or iterator should have a unique \"key\" prop. Check the render method of
Every time you render a list (use map), add a unique key attribute to the list elements (the topmost or "root" element returned from map's callback):
render() {
return (
{this.props.data.map( element => {
// Place the key on to the returned "root" element.
// Also, in real life this should be a separate component...
return
Id (Name):
{element.id}
({element.name})
;
})}
)
}
The official Lists and Keys documentation shows how you should work with lists and the linked reconciliations doc tells the whys.
Basically when React rerenders a component it runs a diff algorithm that finds out what changed between the new and the previous version of the list. Comparison is not always trivial, but if there is a unique key in each element, it can be clearly identified what has changed. See the example in the doc:
- Duke
- Villanova
- Connecticut
- Duke
- Villanova
It is clear that a new element with the key 2014 was added, since we have all the other keys and those weren't changed. Without the keys this would be obscure.
From now it is easy to see:
Math.random().key attribute on componentsThe convention that you should place the key attribute to a component is more of a good practice, because when you iterate a list and want to render an element, that clearly indicates that you should organize that code to a separate component.
key attribute in the loopThe statement you quoted from the docs:
The key should always be supplied directly to the components in the array, not to the container HTML child of each component in the array:
Means that if you render components in a loop, then you should set the key attribute of the component in the loop, like you did it in your EventsTable component:
{this.props.list.map(function (row) {
return (
);
})}
The wrong way is to pass it down to the component where it would set the key on itself:
Event = React.createClass({
displayName: 'Event',
render() {
// Don't do this!
return (
{_.keys(this.props.data).map((x) => {
There is another good example for this in this article.
- 热议问题