简体   繁体   中英

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

Please tell me how to add a unique "key" prop for each child in a list. It is a functional component in react:

<List component="nav">
  {bundlesData.map((bundleItem) => {
    switch (bundleItem) {
      case 'page':
        return pagesNavLink

      case 'menu':
        return (
          <MenuNavLink
            handleClick={handleClick}
            isOpened={isNavLinkOpened}
          />
        )

      default:
        return bundleItem
    }
  })}
</List>

You can use the index to identify each bundleItem :

<List component='nav'>
  {bundlesData.map((bundleItem, index) => {
    switch (bundleItem) {
      case 'page':
        return <div key={index}>{pagesNavLink}</div>;

      case 'menu':
        return (
          <MenuNavLink
            key={index}
            handleClick={handleClick}
            isOpened={isNavLinkOpened}
          />
        );

      default:
        return <div key={index}>{bundleItem}</div>;
    }
  })}
</List>;

One thing you can do with a map function is it can take a second parameter which keeps track of the index. You can then use that index parameter on the list items as a key prop.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

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