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
相关产品推荐
相关产品推荐

