简体   繁体   中英

Each child in a list should have a unique "key" prop error with uuid as key react

I'm getting an "Each child in a list should have a unique "key" prop." in console here specifically (it quotes the first line as the relevant line)

<Dropdown.Menu variant="dark">
  {[
    [0, "prod_name", "Name"],
    [1, "price", "Price"],
    [2, "average_rating", "Rating"],
  ].map((item, i) => (
    <>
      <Dropdown.Item
        as={Button}
        key={uuid.v4()}
        onClick={() => {
          this.setState({ sort: item[0], open: false });
          this.context.sort(item[1], "asc");
        }}
        className={
          this.state.sort === item[0]
            ? "text-black giBold active"
            : "text-light"
        }
      >
        {item[2] + " (ascending)"}
      </Dropdown.Item>
      <Dropdown.Item
        as={Button}
        key={uuid.v4()}
        onClick={() => {
          this.setState({ sort: item[0] + 3, open: false });
          this.context.sort(item[1], "desc");
        }}
        className={
          this.state.sort === item[0] + 3
            ? "text-black giBold active"
            : "text-light"
        }
      >
        {item[2] + " (descending)"}
      </Dropdown.Item>
    </>
  ))}
</Dropdown.Menu>;
               

I changed the key to be uuid since I realised tonnes of id's of different items are going to be the same in hopes that it would fix the error yet it keeps popping up.

Is there something else at play here that I've missed, I tried looking for answers but couldn't find much.

Oh, you just need to add the key to <> , because the key property should be in the first tag in the map function's render section and change the empty tag to <div> because the empty tag can not have any property. Your code should look like this;


[...].map((item, i) => (
    <div key={uuid.v4()}> // this tag's key important for map function
      <Dropdown.Item
        as={Button}
        key={uuid.v4()}
        ...
      >
        {item[2] + " (ascending)"}
      </Dropdown.Item>
      <Dropdown.Item
        as={Button}
        key={uuid.v4()}
        ...
      >
        {item[2] + " (descending)"}
      </Dropdown.Item>
    </div>
  ))}
</Dropdown.Menu>;

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