【问题标题】:Each child in a list should have a unique "key" prop even though I have defined the key即使我已经定义了密钥,列表中的每个孩子都应该有一个唯一的“密钥”道具
【发布时间】:2020-04-27 04:12:29
【问题描述】:

下面是我的反应代码。我有每个人的 key 属性,但我仍然收到错误消息。

**

  • App.js

**

import React, { useState } from "react";
import "./App.css";
import Person from "./Components/Person/Person.js";

const App = props => {
  const [currentState, updatePersonState] = useState({
    Persons: [
      { id: "1", name: "abc", age: "37", hobbies: "Cricket" },
      { id: "2", name: "xyz", age: "33", hobbies: "Cook" },
      { id: "3", name: "pqr", age: "07", hobbies: "Reading" }
    ],
    showContent: true,
    buttonText:'Hide Content'
  });

  let persons = "";
  if (currentState.showContent) {
    persons = currentState.Persons.map((person, index) => (
      <div>
        <Person
          name={person.name}
          age={person.age}
          hobbies={person.hobbies}
          **key={person.id}**
        ></Person>
      </div>
    ));
  }

  const toggleHandler = (event, index) => {
    const showContentNow = currentState.showContent;
    updatePersonState({
      ...currentState,
      showContent: !showContentNow,
      buttonText:currentState.showContent?'Show Content':'Hide Content'
    });
  };
  return (
    <div className="App">
      <h1>Styling Components Dynamically</h1>
      <div>
  <button onClick={toggleHandler}>{currentState.buttonText}</button>
      </div>
      <div> {persons}</div>
    </div>
  );
};
export default App;

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    key 属性需要在根元素上,而不是在子元素上

    https://reactjs.org/docs/lists-and-keys.html#keys

    persons = currentState.Persons.map((person, index) => (
          <div key={person.id}>
            <Person
              name={person.name}
              age={person.age}
              hobbies={person.hobbies}
            ></Person>
          </div>
    

    但是,请注意key 在兄弟姐妹中应该是唯一的,并且在整个应用程序中不需要是唯一的

    【讨论】:

      【解决方案2】:

      不要使用纯整数作为 React 元素的键(React 不喜欢它),这是为了防止出现问题,尤其是当您从不同的循环生成大量元素时。

      由于多个元素可能以 1 作为键(例如),因此可能会导致网站运行过程中出现错误。我建议使用带有一些标识符号的整数,例如...

      "person_element_${person.id}"
      

      基本上是 React 告诉你实施良好的编码实践。

      【讨论】:

      • 感谢您的提示。我正在使用从数据库返回的唯一 ID。为了在此处发布问题,我对值进行了硬编码。
      猜你喜欢
      • 1970-01-01
      • 2021-08-07
      • 2022-11-03
      • 2022-07-22
      • 2019-01-15
      • 2021-06-12
      • 1970-01-01
      • 2023-01-19
      • 2022-11-11
      相关资源
      最近更新 更多