正文从这开始~

总览

当我们从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的更多相关文章

  1. react 报错的堆栈处理

    react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...

  2. 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+的版本里,当在组件 ...

  3. 【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 ...

  4. React报错 :browserHistory doesn't exist in react-router

    由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...

  5. react报错 TypeError: Cannot read property 'setState' of undefined

    代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ...

  6. React报错之Cannot find name

    正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...

  7. React报错之Cannot find namespace context

    正文从这开始~ 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig. ...

  8. React报错之Expected `onClick` listener to be a function

    正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...

  9. 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 ...

随机推荐

  1. Django对接支付宝Alipay支付接口

    最新博客更新见我的个人主页: https://xzajyjs.cn 我们在使用Django构建网站时常需要对接第三方支付平台的支付接口,这里就以支付宝为例(其他平台大同小异),使用支付宝开放平台的沙箱 ...

  2. Go微服务框架go-kratos实战02:proto 代码生成和编码实现步骤

    在上一篇 kratos quickstart 文章中,我们直接用 kratos new 命令生成了一个项目. 这一篇来看看 kratos API 的定义和使用. 一.kratos 中 API 简介 1 ...

  3. bootstrap 4.0 dropdown 找不到popper.js 的解决方案

    最近项目中升级bootstrap 由3.3.7版 升了4.0版本 发现 dropdown 找不到popper.js 解决办法:npm install -save popper 下载完之后,查看node ...

  4. 10分钟快速部署camunda BPM开源版

    安装部署Camunda BPM有多种方式,基于Camunda独立web应用程序安装部署是最简单的一种方式,您只需要有tomcat即可. 本文档将指导您安装和配置Camunda独立web应用程序,快速体 ...

  5. 聊聊 C++ 和 C# 中的 lambda 玩法

    这几天在看 C++ 的 lambda 表达式,挺有意思,这个标准是在 C11标准 加进去的,也就是 2011 年,相比 C# 2007 还晚了个 4 年, Lambda 这东西非常好用,会上瘾,今天我 ...

  6. 3.shell脚本循环试题

    shell脚本循环试题 1.计算从1到100所有整数的和 #!/bin/bash a=0 for i in {1..100} #1到100 #每次循环变量i的值也为循环次数 do a=$[ $a + ...

  7. 一文详解JackSon配置信息

    背景 1.1 问题 Spring Boot 在处理对象的序列化和反序列化时,默认使用框架自带的JackSon配置.使用框架默认的,通常会面临如下问题: Date返回日期格式(建议不使用Date,但老项 ...

  8. babeljs源码

    babel.min.js!function(e,t){"object"==typeof exports&&"object"==typeof mo ...

  9. 搭建ceph分布式文件系统

      1. 准备4台虚拟机 ceph 192.168.66.93 管理osd,mon节点 ceph-node1 192.168.66.94 osd节点 ceph-node2 192.168.66.95 ...

  10. NC24622 Brownie Slicing

    NC24622 Brownie Slicing 题目 题目描述 Bessie has baked a rectangular brownie that can be thought of as an ...