javascript - ESLint 错误:列表中的每个孩子都应该有一个唯一的“关键”道具
问题描述
我有一个如下所示的 JSON 字符串。该字符串具有 \n 用于下一行。
data:{a:"A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming. Modern computers have the ability to follow generalized sets of operations, called programs. These programs enable computers to perform an extremely wide range of tasks. A "complete" computer including the hardware, the operating system (main software), and peripheral equipment required and used for "full" operation can be referred to as a computer system. This term may as well be used for a group of computers that are connected and work together, in particular, a computer network or computer cluster.\nComputers are used as control systems for a wide variety of industrial and consumer devices. This includes simple special purpose devices like microwave ovens and remote controls, factory devices such as industrial robots and computer-aided design, and also general-purpose devices like personal computers and mobile devices such as smartphones. The Internet is run on computers and it connects hundreds of millions of other computers and their users."}
我在 React 中使用它,如下所示:
const b = data.a.split("\n");
return(
<P>
b.map((p,index)=>({p}<br key={index}/>))
</p>
对于上面的代码,我收到了 ES lint 警告。警告如下。
Each child in a list should have a unique "key" prop.
我怎样才能避免警告?我需要段落标签中的文本,并且文本中的每个换行符都(\n)
替换为<br/>
解决方案
b.map((p,index)=>(<p key={index}>{p}</p>))
您需要包装元素上的密钥。只需使用p
标签,您就可以免费获得换行符。;)
不过,使用索引作为键是一个坏主意是有原因的。
推荐阅读
- css - Bulma Navbar-单击时的项目颜色
- angular - 如何使用 DOCUMENT for public-api 导出 Angular 10 防护
- javascript - React js材料ui文本字段能够标记用户
- spring - 如何在 authenticationManagerBuilder 上注册多个 UserDetailsService
- c++ - 如何正确制作班级成员大二维 C 数组?
- qt - 如何自定义 Qt Items 的绘制事件?
- jenkins - 无法使用 Helm 启动 Jenkins
- amazon-web-services - 如何将多个实例添加到 aws_network_interface_sg_attachment?
- javascript - 为什么我无法捕获 node-postgres 引发的错误?
- python - 如何避免将“全局”与 asyncio(电视节目)一起使用?