提问者:小点点

列表中的每个子项都应该有一个唯一的“键”道具,即使我已经定义了键


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

**

  • 应用程序。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;

共2个答案

匿名用户

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>

但是,请注意,在同级中应该是唯一的,而不需要在整个应用程序中是唯一的

匿名用户

不要使用普通整数作为React元素的键(React不喜欢它),这是为了防止问题,尤其是当你有很多元素从不同的循环中生成时。

由于多个元素可能有1作为键(例如),它可能会导致错误沿网站的运行。我建议使用带有标识符号的整数,如...

"person_element_${person.id}"

基本上是告诉您实现良好的编码实践。