【问题标题】:React-Warning-Keys with no List or .map没有 List 或 .map 的 React-Warning-Keys
【发布时间】:2026-02-08 14:45:01
【问题描述】:

React 文档说A “key” is a special string attribute you need to include when creating lists of elements.

但是我在没有呈现列表的情况下收到反应键警告,我不知道为什么。

我有一个名为 ExpandableCard.js 的组件,它有条件地呈现标题子项:

  // ExpandleCard return call
  ...
  return <Card className={classes.expandableCard} classes={{ root: classes.cardRoot }}>
    <div className={classes.cardHeader}>
      { props.header ? props.header : null }
      <div className={classes.headerActions}>
        {
          expanded
            ? <KeyboardArrowUp onClick={() => { setExpanded(false) }} />
            : <KeyboardArrowDown onClick={() => { setExpanded(true) }} />
        }
        { props.editable && props.onRemove ? <Close onClick={props.onRemove} /> : null }
      </div>
    </div>
    ...
    // renders children
   <Card/>

当我使用合成正常渲染组件时:

...
return <ExpandableCard header={<h4 className={c.cardTitle}>{t('record_summary.summary')}</h4>}>
    {Object.keys(displayKeys).map((d, i) => {
      return <DetailRow title={d} value={displayKeys[d]} key={i} />
    })}
  </ExpandableCard>
}

我收到反应警告错误

react-dom.development.js:530 Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/docs/lists-and-keys.html for more information.
    in div
    in div (created by ForwardRef(Paper))
    in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
    in WithStyles(ForwardRef(Paper)) (created by ForwardRef(Card))
    in ForwardRef(Card) (created by WithStyles(ForwardRef(Card)))
    ...

我最初认为这是我使用 DetailRow 子项的映射渲染的列表出现错误,但我发现当我使用键渲染 header 道具时,错误消失了:

return &lt;ExpandableCard header={&lt;h4 key={'header-for-record-summary'} ...

为什么 react 会警告我有关未映射到列表中的 dom 元素上的键?

【问题讨论】:

  • 我遇到了同样的问题。我也在使用 HOC。你找到解释了吗?
  • 是的,我做到了,这是一个 babel 问题,我会发布它作为答案。希望和你的问题一样
  • 感谢您的快速回复。你为我节省了很多时间!

标签: reactjs list key


【解决方案1】:

所以我发现我的问题在于在开发环境中启用 @babel/plugin-transform-react-inline-elements

通过将其更改为仅在生产中启用,我的错误消失了:

module.exports = {
  plugins: [...],
  presets: [...],
  env: {
    production: {
      plugins: [
        '@babel/plugin-transform-react-inline-elements'
      ]
    }
  }
}

根据babel documentation on the plugin

这种转换应该只在生产中启用(例如,在缩小代码之前),因为虽然它提高了运行时性能,但它使警告消息更加神秘,并跳过了在开发模式下发生的重要检查,包括 propTypes。

【讨论】: