React 警告:数组或迭代器中的每个子项都应该有一个唯一的 "key" 属性。检查 `App` 的渲染方法

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

我收到了那个错误,但我正在定义一个密钥。这是我的 App.js 它抱怨的。

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')}
                        }
                    }
                }
            }
        `,
    },
});

更正此问题的最简单方法是使键脱离地图的索引:

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

那么,你就不用担心edge.node.id的值有多独特了。 key 只需要在所有 AccountTable 兄弟姐妹的上下文中是唯一的。它不需要是全局唯一的。因此,该索引运行良好。

但是,如果您有一个基于对象的稳定 ID,那显然更好。

我使用的解决方案是提取relay fragment的底层id作为key

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