React报错之Encountered two children with the same key
正文从这开始~
总览
当我们从map()方法返回的两个或两个以上的元素具有相同的key属性时,会产生"Encountered two children with the same key"错误。为了解决该错误,为每个元素的key属性提供独一无二的值,或者使用索引参数。
这里有个例子来展示错误是如何发生的。
// App.js
const App = () => {
// ️ name property is not a unique identifier
const people = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
{id: 3, name: 'Alice'},
];
/**
* ️ Encountered two children with the same key, `Alice`.
* Keys should be unique so that components maintain their identity across updates.
* Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
*/
return (
<div>
{people.map(person => {
return (
<div key={person.name}>
<h2>{person.id}</h2>
<h2>{person.name}</h2>
</div>
);
})}
</div>
);
};
export default App;
上述代码片段的问题在于,我们在每个对象上使用name属性作为key属性,但是name属性在整个对象中不是独一无二的。
index
解决该问题的一种方式是使用索引。它是传递给map方法的第二个参数。
const App = () => {
const people = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
{id: 3, name: 'Alice'},
];
// ️ now using index for key
return (
<div>
{people.map((person, index) => {
return (
<div key={index}>
<h2>{person.id}</h2>
<h2>{person.name}</h2>
</div>
);
})}
</div>
);
};
export default App;
我们传递给Array.map方法的函数被调用,其中包含了数组中的每个元素和正在处理的当前元素的索引。
索引保证是唯一的,但是用它来做
key属性并不是一个最好的做法。因为它不稳定,在渲染期间会发生变化。
唯一标识
更好的解决方案是,使用一个能唯一标识数组中每个元素的值。
在上面的例子中,我们可以使用对象上的id属性,因为每个id属性保证是唯一的。
// App.js
const App = () => {
const people = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
{id: 3, name: 'Alice'},
];
// now using the id for the key prop
return (
<div>
{people.map(person => {
return (
<div key={person.id}>
<h2>{person.id}</h2>
<h2>{person.name}</h2>
</div>
);
})}
</div>
);
};
export default App;
使用id作为key属性好多了。因为我们保证了对象id属性为1时,name属性总是等于Alice。
React使用我们传递给
key属性的值是出于性能方面的考虑,以确保它只更新在渲染期间变化的列表元素。
当数组中每个元素都拥有独一无二的key时,React会更容易确定哪些列表元素发生了变化。
你可以使用index作为key属性。然而,这可能会导致React在幕后做更多的工作,而不是像独一无二的id属性那样稳定。
尽管如此,除非你在渲染有成千上万个元素的数组,否则你很有可能不会注意到使用索引和唯一标识符之间有什么区别。
React报错之Encountered two children with the same key的更多相关文章
- react 报错的堆栈处理
react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...
- vue使用v-for时vscode报错 Elements in iteration expect to have 'v-bind:key' directives
vue使用v-for时vscode报错 Elements in iteration expect to have 'v-bind:key' directives Vue 2.2.0+的版本里,当在组件 ...
- 【spring boot】使用定时任务@Scheduled 报错:Encountered invalid @Scheduled method 'dealShelf': Cron expression must consist of 6 fields (found 7 in "0 30 14 * * ? *")
在spring boot中使用使用定时任务@Scheduled 报错: org.springframework.beans.factory.BeanCreationException: Error c ...
- React报错 :browserHistory doesn't exist in react-router
由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...
- react报错 TypeError: Cannot read property 'setState' of undefined
代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ...
- React报错之Cannot find name
正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...
- React报错之Cannot find namespace context
正文从这开始~ 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig. ...
- React报错之Expected `onClick` listener to be a function
正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...
- React报错:Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix,
今天在开发时报了以下错误,记录一下 我们不能在组件销毁后设置state,防止出现内存泄漏的情况 出现原因直接告诉你了,组件都被销毁了,还设置个锤子的state啊 解决方案: 利用生命周期钩子函数:co ...
随机推荐
- 使用pdfcrack & crunch暴力破解PDF密码
crunch是密码字典生成器,可以根据指定的字符来生成组合密码字典. pdfcrack是Linux下一个PDF暴力破解密工具,可以使用crunch生成的密码字典来暴力破解PDF文件的密码. 注:没有强 ...
- Fail2ban 配置详解 监禁配置(jail.conf)
### # 包含配置 ### [INCLUDES] # after = # 在加载本配置文件之后再加载指定的独立配置文件. before = paths-debian.conf # 在加载本配置文件之 ...
- JetBrains IDE全新UI预览版来了,要做简洁与强大兼顾的IDE
5月23日,JetBrains发布了一篇博文,透露他们正在实现一套全新的界面界面. 他们认为目前行业中的用户界面趋势已经发生了演变,很多新用户认为JetBrains IDE的界面过于笨重,而且过时.所 ...
- re学习笔记
re学习笔记 学习链接: https://regexlearn.com/zh-cn/learn \w: 数字字母下划线 \W: 非\w \d \D: !\d \s: space cha \S: !\s ...
- CAD图在线Web测量工具代码实现(测量距离、面积、角度等)
CAD如今在各个领域均得到了普遍的应用并大大提高了工程技术人员的工作效率.在桌面端,AutoCAD测量工具已经非常强大:然后在Web端,如何准确.快速的对CAD图在Web进行测量呢? 功能 能Web在 ...
- 520到了,作为一个python程序员,必须整点肤白貌美的爬虫代码给你们~
马上520就快到啦~ 整点好看的给你们看下~ 直接开搞~ 代码流程 模拟浏览器向服务器发送一个http请求,网站接收到请求后返回数据.在写爬虫代码的时候一定先要去模拟浏览器访问,因为现在的网站当接收到 ...
- sql server 开启一个事务
开启事务,回滚 /*============================================================== */ /* Date : 2020年11月18日 11 ...
- Tapdata Cloud 2.1.5来啦:新增支持Amazon RDS数据库,错误日志查询更便捷,Agent部署细节再优化
需求持续更新,优化一刻不停--Tapdata Cloud 2.1.5 来啦! 最新发布的版本中,数据连接再上新,同时新增任务报错相关信息快速查询入口,开始支持 JVM 参数自定义设置. 更 ...
- VS code 远程连接服务器步骤
①安装VS code,并连接远程服务器(本地也需要有ssh).参考 ②免密钥登录设置,参考 具体步骤:WIN+R -->cmd, 输入ssh-keygen,然后一直Enter,最终生成公钥和私钥 ...
- Linux为所有用户安装Miniconda
如果以root身份默认安装,后续普通用户再安装的话,是直接用不起来的,需要改些东西,所以在安装时最好全局安装,所有用户都可用 执行安装脚本:sudo bash Miniconda3-latest-Li ...