已为列表所有组件设置唯一key仍报React unique key prop警告如何解决
问题原因
你外层options.map返回的直接根节点是简写形式的React Fragment(<></>),你没有给这个根节点设置key,你加的key都在Fragment内部的子元素上,不符合React对列表渲染的key要求:map方法返回的直接顶层元素必须绑定唯一key值。同时简写的<></>不支持添加任何属性,无法绑定key。
修复方案
把外层map返回的简写Fragment替换成完整的React.Fragment写法,给它绑定key即可,原来h2上的key可以直接删除:
export default function ShortcutArea({handler, ...props}){ const ShortcutClickHandler = (e) => { handler.setEncoding(e); } return (<> { options.map((item, index) => {/* 给顶层Fragment加key,改用完整写法 */} <React.Fragment key={index}> <h2>{item.title}</h2> {item.data.map((shortcut,idx) => <ShortcutSelection key = {index + "_" + idx} onClick={ShortcutClickHandler} data-currentencoding={shortcut.from} data-targetencoding={shortcut.to} data-payload={shortcut.payload} data-action={shortcut.action} >{shortcut.displaytext} </ShortcutSelection> )} </React.Fragment> ) } </>) }
可选优化建议
如果你的options数组的每个item,以及item.data下的每个shortcut都有唯一业务id,建议优先用业务id代替数组下标作为key值,避免数组增删排序时出现组件状态错乱的问题。
内容的提问来源于stack exchange,提问作者bmjeon5957
相关产品推荐
相关产品推荐

