React Warning: Each child in an array or iterator should have a unique “key” prop. Check the render method of `App`

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

I'm getting that error, but I'm defining a key. Here's my App.js that it's complaining about.

import React from 'react'; import Relay from 'react-relay'; import AccountTable from './AccountTable';  class App extends React.Component {   render() {     return (       <div>         <h1>Account list</h1>           {this.props.viewer.accounts.edges.map(edge =>             <AccountTable key={edge.node.id} account={edge.node} />           )}       </div>     );   } }  export default Relay.createContainer(App, {     fragments: {         viewer: () => Relay.QL`             fragment on User {                 accounts(first: 10) {                     edges {                         node {                             ${AccountTable.getFragment('account')}                         }                     }                 }             }         `,     }, }); 

回答1:

The easiest way to correct this is to base the key off the index of the map:

{this.props.viewer.accounts.edges.map((edge, i) =>     <AccountTable key={i} account={edge.node} /> )} 

Then, you don't have to worry about how unique the value of edge.node.id is. The key only needs to be unique in the context of all the AccountTable siblings. It doesn't need to be globally unique. So, the index works well.

However, if you have a stable id that is based off of the object, that is obviously better.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!