代码之家  ›  专栏  ›  技术社区  ›  bajji

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

  •  -1
  • bajji  · 技术社区  · 6 年前

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

    **

    **

    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 回复  |  直到 6 年前
        1
  •  4
  •   Vicky Gonsalves    6 年前

    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>
    

    钥匙 在同级中应该是唯一的,在整个应用程序中不需要是唯一的

        2
  •  1
  •   MrCharls    6 年前

    不要使用纯整数作为React元素的键(React不喜欢这样),这是为了防止出现问题,特别是当有很多元素是从不同的循环生成的时候。

    因为多个元素 1个 作为密钥(例如),它可能会在网站运行过程中引起错误。我建议使用带一些标识符号的整数,比如。。。

    "person_element_${person.id}"