You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React报错:列表子元素需唯一key属性,排查无果求解答

解决React "Each child in a list should have a unique 'key' prop." 报错问题

问题根源

你代码里的报错出在notes.map循环生成列表的部分:你用空Fragment(<>)包裹了<Note>组件,但这个Fragment才是map返回的列表直接子元素。你把key加在了内部的<Note>上,React无法识别——React要求列表的每一项顶层元素必须携带唯一key。

两种解决办法

办法1:移除多余的Fragment

因为你的Fragment里只包含一个<Note>组件,完全没必要额外包裹,直接返回<Note>并给它加key即可:

<div className="notes">
  {notes.map((note) => (
    <Note
      key={note.id}
      id={note.id}
      title={note.title}
      text={note.text}
      date={note.date}
      deleteNote={deleteNote}
      closeNote={closeModal}
      openModal={openModal}
      modalIsOpen={modalIsOpen}
    />
  ))}
</div>

办法2:给完整Fragment添加key

如果确实需要保留Fragment(比如后续要在里面加更多元素),不能用短语法的<>,必须写完整的<React.Fragment>并绑定key:

<div className="notes">
  {notes.map((note) => (
    <React.Fragment key={note.id}>
      <Note
        id={note.id}
        title={note.title}
        text={note.text}
        date={note.date}
        deleteNote={deleteNote}
        closeNote={closeModal}
        openModal={openModal}
        modalIsOpen={modalIsOpen}
      />
    </React.Fragment>
  ))}
</div>

额外说明

你Modal里的条件渲染部分不属于循环生成的列表,有没有key都不会触发这个报错,完全不用处理。

内容的提问来源于stack exchange,提问作者Doron Barel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 12:01:42