简体   繁体   中英

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

Following this post, Loop inside React JSX , I wanted to simplify my code by rendering components via a loop. However, I am getting the warning: Warning Each child in a list should have a unique "key" prop.

What should the key be to ensure it will be unique? I have tried naming it payload[i] but that did not result in a unique name. See code below and a sample of payload data:

      var states = [];
      for(var i = 0; i < payload.length; i++){
        console.log("i " + i);
        states.push(
        <Typography sx={{ fontSize: 14 }} color= {payload[i].fill } >
        {`${payload[i].dataKey} : ${payload[i].value}`}
      </Typography>  )
      }
      return (
      \\ other code
      {states}

      );

在此处输入图像描述

Try using payload[i].dataKey or payload[i].name if you know that it will be unique across your items. Otherwise if the order will not change between renders (you don't change the array by adding/removing items or sorting it), you can use i as the key.

You were using payload[i] which translates to [object Object] as a string, for all the elements ( Object.toString() will return [object Object] ) -- so it was not unique.

This is needed for the reconciliation algorithm of React Virtual DOM (when having multiple nodes, you need a unique key for them so it will not update all of them when only one changes).

When children have keys, React uses the key to match children in the original tree with children in the subsequent tree.

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:

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.

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.

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.

It's an indentifier that it's used by react to keep track about optimizing re-rendering and internal state of elements in the dom.

It should be an identifier of the object itself, not the index for example. Find an unique string that could fit this purpose in the list, like ¿dataKey?

  var states = [];
  for(var i = 0; i < payload.length; i++){
    console.log("i " + i);
    states.push(
    <Typography key={payload[i].dataKey} sx={{ fontSize: 14 }} color= {payload[i].fill } >
    {`${payload[i].dataKey} : ${payload[i].value}`}
  </Typography>  )
  }
  return (
  \\ other code
  {states}

  );

You need to add a key in the tag with a unique id for each item in the loop, example:

<ul>

array.map((value, index) => {

   return(
     
       <li key={index}>
           {value}
       </li> 
   );

});

</ul>

When you create a list, you'll be given a warning that a key should be provided for list items. A “key” is a special string attribute you need to include when creating lists of elements. Read here for more information: https://reactjs.org/docs/lists-and-keys.html

Let's assume that a component has a loop in JSX and for example, this loop depends on an array. If the array is modified, then React has to re-render the component and re-run the loop. React has to know which items in the array are modified to be able to correctly render the output of the loop. That's why we need key . Like this:

Array.map( ( item , index )=>(
<div key={item.id}> { item.name } </div>
))

The key has to be unique. You may use item's index but this is generally a bad practice. Although it is unique, but when - for example - you remove an array item, the indexes change for every item.

A good practice is to always have a unique id field for your items (only if you know the array is going to be modified in the future. If not, using index is OK as well). There are bunch of libraries that help you generate a uuid (if it hasn't been already done on the server-side). Check UUID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM