繁体   English   中英

警告列表中的每个孩子都应该有一个唯一的“关键”道具

[英]Warning Each child in a list should have a unique "key" prop

我有一个对象数组,我用它们来列出带有地图的页面中的值。 但我不时收到此错误。

警告:列表中的每个孩子都应该有一个唯一的“关键”道具。

虽然键是唯一的。

也许有人知道这里可能出了什么问题?

const items = [
  {key: 1, name: 'Item one', value: 34 },
  {key: 2, name: 'Item two', value: 45 },
  {key: 3, name: 'Item three', value: 12 },
]

const item = ({ name, value, key }) => (
    <div>
      <p>{name}</p>
      <p>{value}</p>
    </div>
  )

return(
 <div>
   {items.map(i => item(i))}
 </div>
)

item需要是一个组件,并且 React 组件名称需要大写。 您的Item组件需要一个对象。 您的“钥匙”需要放在映射的组件上。

 // Accepts items // From each object in the array it gets the // key, name, and value, and returns a new // component function Example({ items }) { return ( <div> {items.map(item => { const { key, value, name } = item; return <Item key={key} value={value} name={name} /> })} </div> ); } // Accepts an object - returns some JSX to be rendered function Item({ name, value }) { return ( <div> <p>{name}</p> <p>{value}</p> </div> ); } const items = [ {key: 1, name: 'Item one', value: 34 }, {key: 2, name: 'Item two', value: 45 }, {key: 3, name: 'Item three', value: 12 }, ]; ReactDOM.render( <Example items={items} />, document.getElementById('react') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

您只需要像我在下面的代码中所做的那样传递子 div 中的密钥。 我认为它将消除您在下面的错误

import React from 'react';
import './style.css';

export default function App() {
  const items = [
    { key: 1, name: 'Item one', value: 34 },
    { key: 2, name: 'Item two', value: 45 },
    { key: 3, name: 'Item three', value: 12 },
  ];
  const item = ({ name, value, key }) => (
    <div key={key}>
      <p>{name}</p>
      <p>{value}</p>
    </div>
  );
  return <div>{items.map((i) => item(i))}</div>;
}

供参考: https ://reactjs.org/docs/lists-and-keys.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM