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 ...
随机推荐
- MongoDB 各项命名规范
每日一句 Progress is the result of a bunch of failures. 进步是不断失败的成果. 概述 MongoDB涉及到的一些比如集合啥的命令规范. 集合的命名规范 ...
- 深度学习与CV教程(2) | 图像分类与机器学习基础
作者:韩信子@ShowMeAI 教程地址:http://www.showmeai.tech/tutorials/37 本文地址:http://www.showmeai.tech/article-det ...
- Spring Security OAuth正式终止维护,已从官网下架
Spring Security团队正式宣布Spring Security OAuth终止维护. 目前官网的主页已经高亮提醒彻底停止维护. 旧的Spring Security OAuth项目终止到2.5 ...
- ELK 是什么?
E指的是ElasticSearch Elasticsearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasticsearch ...
- python变量名下划线
xx: 公有变量 _x: 单前置下划线,保护变量,私有化属性或方法,不能用于'from module import *' 以单下划线开头的表示的是protected类型的变量.即保护类型只能允许其/类 ...
- fpm工具安装
概述 最近在对机房的编译环境做整理,过程曲折而痛苦,记录一下. 之前的一个老项目,在打包的时候用到了一个叫做fpm的工具. 编译环境涉及centos6和centos7,在新的编译环境的过程中,如何安装 ...
- C语言- 基础数据结构和算法 - 栈的顺序存储
听黑马程序员教程<基础数据结构和算法 (C版本)>, 照着老师所讲抄的, 视频地址https://www.bilibili.com/video/BV1vE411f7Jh?p=1 喜欢的朋友 ...
- 开源流程引擎osworkflow、jbpm、activiti、flowable、camunda哪个好?
市场上比较有名的开源流程引擎有osworkflow.jbpm.activiti.flowable.camunda.其中:Jbpm4.Activiti.Flowable.camunda四个框架同宗同源, ...
- 一文掌握软件安全必备技术 SAST
上一篇文章中,我们讨论了软件供应链的概念并了解到近年来软件供应链安全事件层出不穷.为了保障软件供应链安全,我们需要了解网络安全领域中的一些主要技术.本篇文章将介绍其中一个重要技术--SAST. 当开发 ...
- $.fn解析
$.fn是指jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效. 如扩展$.fn.abc(),即$.fn.abc()是对jquery扩展了一个abc方法,那么后面你的每一个 ...