解决React报错Encountered two children with the same key

目录
  • 总览
  • index
  • 唯一标识

总览

当我们从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属性那样稳定。

尽管如此,除非你在渲染有成千上万个元素的数组,否则你很有可能不会注意到使用索引和唯一标识符之间有什么区别。

原文链接:bobbyhadz.com/blog/react-…

以上就是解决React报错Encountered two children with the same key的详细内容,更多关于React报错same key的资料请关注我们其它相关文章!

(0)

相关推荐

  • 解决React报错useNavigate() may be used only in context of Router

    目录 总览 useNavigate Jest replace 总览 当我们尝试在react router的Router上下文外部使用useNavigate 钩子时,会产生"useNavigate() may be used only in the context of a Router component"警告.为了解决该问题,只在Router上下文中使用useNavigate 钩子. 下面是一个在index.js文件中将React应用包裹到Router中的例子. // index.j

  • 解决React报错Style prop value must be an object

    目录 总览 映射 提取 总览 在React中,当我们为元素的style 属性传递字符串时,会产生"Style prop value must be an object"警告.为了解决该警告,使用从属性到值的映射.比如说,style={{paddingLeft: '15px'}} . 这里有个例子来展示错误是如何发生的. // App.js const App = () => { // ️ Style prop value must be an object eslint(reac

  • 解决React报错Cannot assign to 'current' because it is a read-only property

    目录 总览 正确的泛型 DOM元素 总览 当我们用一个null值初始化一个ref,但在其类型中不包括null时,就会发生"Cannot assign to 'current' because it is a read-only property"错误.为了解决该错误,请在ref的类型中包含null.比如说,const ref = useRef<string | null>(null) . 这里有个例子来展示错误是如何发生的. // App.tsx import {useEf

  • 解决React报错No duplicate props allowed

    目录 总览 className 总结 总览 当我们为相同的组件传递相同的属性多次时,就会导致"No duplicate props allowed"警告.为了解决该警告,请确保只传递一次该属性.比如说,如果传递多次className属性,将它们连接成一个空格分隔的字符串. 下面的示例用来展示如何导致警告的. const App = () => { // ️ JSX elements cannot have multiple attributes with the same nam

  • 解决React报错Functions are not valid as a React child

    目录 总览 调用函数 总结 总览 产生"Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render."错误 通常是因为以下两个原因: 从render中返回一个函数引用而不是一个组件. 使用 react router 路由作为<Route path="/about" el

  • 解决React报错The tag is unrecognized in this browser

    目录 总览 确保标签存在 小写字母开头 总览 当我们使用一个在浏览器中不存在的标签或以小写字母开头的组件名称时,会产生"The tag is unrecognized in this browser"React警告.为了解决该问题,只使用有效的标签名称,并将你的组件的第一个字母大写. 这里有个例子来展示错误是如何发生的. // App.js const App = () => { // ️ Warning: The tag <p1> is unrecognized i

  • 解决React报错React.Children.only expected to receive single React element child

    目录 总览 React片段 DOM元素 总览 当我们把多个子元素传递给一个只期望有一个React子元素的组件时,会产生"React.Children.only expected to receive single React element child"错误.为了解决该错误,将所有元素包装在一个React片段或一个封闭div中. 这里有个示例来展示错误是如何发生的. // App.js import React from 'react'; function Button(props)

  • 解决React报错Parameter 'props' implicitly has an 'any' type

    目录 总览 安装类型文件 声明类型 泛型 重新安装 总览 当我们没有为函数组件或者类组件的props声明类型,或忘记为React安装类型声明文件时,会产生"Parameter 'props' implicitly has an 'any' type"错误.为了解决这个错误,在你的组件中明确地为props对象设置一个类型. 安装类型文件 你首先要确定的是你已经安装了React类型声明文件.在项目的根目录下打开终端,并运行以下命令. # ️ with NPM npm install --s

  • 解决React报错Unexpected default export of anonymous function

    目录 总览 命名 注释单行规则 总结 总览 当我们尝试使用默认导出来导出一个匿名函数时,会导致"Unexpected default export of anonymous function"警告.为了解决该错误,在导出函数之前,为函数赋予一个名称. 这里有个例子来展示警告是如何发生的. // Header.js // ️ default export for anonymous function // ️ Unexpected default export of anonymous

  • 解决React报错Expected an assignment or function call and instead saw an expression

    目录 正文 显式返回 隐式返回 返回对象 正文 当我们忘记从函数中返回值时,会产生"Expected an assignment or function call and instead saw an expression"错误.为了解决该错误,确保显式地使用return语句或使用箭头函数隐式返回. 下面有两个示例来展示错误是如何产生的. // App.js const App = props => { const result = ['a', 'b', 'c'].map(el

  • 解决React报错You provided a `checked` prop to a form field

    目录 总览 defaultChecked onChange 初始值 总览 当我们在多选框上设置了checked 属性,却没有onChange 处理函数时,会产生"You provided a checked prop to a form field without an onChange handler"错误.为了解决该错误,可以使用defaultChecked 属性,或者在表单字段上设置onChange 属性. 这里有个例子用来展示错误是如何发生的. // App.js export

随机推荐