Reactjs 是否可以使用唯一、稳定的函数(例如组件)而不是字符串作为键?

Reactjs 是否可以使用唯一、稳定的函数(例如组件)而不是字符串作为键?,reactjs,Reactjs,在回答时,我在以下代码中使用索引作为键: const menuItems = [ { Page: ActiveDeals, Icon: Home }, { Page: UpcomingDates, Icon: CalendarToday }, { Page: DealsPipeline, Icon: FilterList } ]; const mappedMenuItems = menuItems.map((menuItem, index) => ( <Dashboa

在回答时,我在以下代码中使用索引作为键:

const menuItems = [
  { Page: ActiveDeals, Icon: Home },
  { Page: UpcomingDates, Icon: CalendarToday },
  { Page: DealsPipeline, Icon: FilterList }
];
const mappedMenuItems = menuItems.map((menuItem, index) => (
  <DashboardListItem
    key={index}
    {...menuItem}
    ShownPage={this.state.shownPage}
    setShownPage={this.setShownPage}
  />
));
在本例中,这很好,因为顺序不是易变的,但理想情况下,我会为唯一键使用特定于数据的内容。在本例中,数据中没有或不需要任何字符串标识符。该数组中每个条目的主要独特之处是通过Page属性传递给每个menuItem的内容组件。此函数对于每个菜单项都是唯一的,并且随着时间的推移会保持稳定,不会随着重新渲染而更改,因此在渲染组件列表/数组时,它符合键属性的大多数标准,但文档中指出字符串是首选键类型

所以我想知道,使用函数作为键可以吗


在发布问题的同时,我也加入了我自己的答案,但是如果您有什么需要补充的,请随意回答-特别是如果您知道React团队推荐字符串作为键的具体原因。

要回答这个问题,我首先查看了文档,其中明确地建议键是字符串

“键”是一个特殊的字符串属性,您需要在 创建元素列表

而且在

选择键的最佳方法是使用唯一标识的字符串 同级中的列表项。当你没有稳定的身份证时 渲染项时,您可以使用项索引作为键作为最后手段

到目前为止,文档提到了字符串和整数,例如索引,但我仍然想知道使用其他东西是否有任何危害。所以下一步要看的是源代码

为了找到正确的源代码,我在应该有一个键的地方留下了一个键,然后使用结果消息列表中的每个子项都应该有一个唯一的。。。搜索GitHub存储库。这让我想到了。然后,我发现以下功能与我的问题相关:

  function mapRemainingChildren(
    returnFiber: Fiber,
    currentFirstChild: Fiber,
  ): Map<string | number, Fiber> {
    // Add the remaining children to a temporary map so that we can find them by
    // keys quickly. Implicit (null) keys get added to this set with their index
    // instead.
    const existingChildren: Map<string | number, Fiber> = new Map();

    let existingChild = currentFirstChild;
    while (existingChild !== null) {
      if (existingChild.key !== null) {
        existingChildren.set(existingChild.key, existingChild);
      } else {
        existingChildren.set(existingChild.index, existingChild);
      }
      existingChild = existingChild.sibling;
    }
    return existingChildren;
  }
所以这里existingChildren是一个使用键的地图。可以支持作为键的函数,我尝试使用menuItem.Page作为键,它似乎工作得很好,但代码中的类型清楚地表明字符串| number是键的类型

现在我的结论是,应该避免使用字符串| number以外的类型,因为消息来源声明这是一种限制,并且可能有一些我不知道的原因,可能是因为未来的计划可能会使这种限制比目前看起来更重要,但我仍然好奇,是否有更强有力的理由来限制用于键的类型