我正在构建一个React组件,它接受JSON数据源并创建一个可排序的表。 每个动态数据行都有一个唯一的键分配给它,但我仍然得到一个错误:

数组中的每个子元素都应该有一个唯一的“key”道具。 检查TableComponent的渲染方法。

我的TableComponent渲染方法返回:

<table>
  <thead key="thead">
    <TableHeader columns={columnNames}/>
  </thead>
  <tbody key="tbody">
    { rows }
  </tbody>
</table>

TableHeader组件是单行,也有一个唯一的键赋给它。

行中的每一行都是由一个具有唯一键的组件构建的:

<TableRowItem key={item.id} data={item} columns={columnNames}/>

TableRowItem看起来是这样的:

var TableRowItem = React.createClass({
  render: function() {

    var td = function() {
        return this.props.columns.map(function(c) {
          return <td key={this.props.data[c]}>{this.props.data[c]}</td>;
        }, this);
      }.bind(this);

    return (
      <tr>{ td(this.props.item) }</tr>
    )
  }
});

是什么导致唯一键道具错误?


当前回答

我也遇到过类似的问题,但不确切。尝试了所有可能的解决方案,都无法摆脱这个错误

数组中的每个子元素都应该有一个唯一的“key”道具。

然后我尝试在不同的本地主机上打开它。我不知道怎么回事,但它奏效了!

其他回答

If you are getting error like :

> index.js:1 Warning: Each child in a list should have a unique "key" prop.

Check the render method of `Home`. See https://reactjs.org/link/warning-keys for more information.

Then Use inside map function like:

  {classes.map((user, index) => (
              <Card  **key={user.id}**></Card>
  ))}`enter code here`

react中定义唯一键的最佳解决方案: 在映射内部,初始化名称post,然后用key={post定义键。Id}或者在我的代码中,你看到我定义了名称item,然后我定义key by key={item. Id}:

< div className = "容器" > {职位。地图(项= > ( <div className="card border-primary mb-3" key={item.id}> . < div className = " card-header " > {item.name} < / div > <div className="card-body" > < h4 className = " card-title " > {item.username} < / h4 > < p className = "卡片文本" > {item.email} < / p > < / div > < / div > )} < / div >

当你对呈现的项目没有稳定的id时,你可以使用项目索引作为关键字作为最后的手段:

const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
   <li key={index}>
      {todo.text}
   </li>
);

请参考列表和键-反应

var TableRowItem = React.createClass({
  render: function() {

    var td = function() {
        return this.props.columns.map(function(c, i) {
          return <td key={i}>{this.props.data[c]}</td>;
        }, this);
      }.bind(this);

    return (
      <tr>{ td(this.props.item) }</tr>
    )
  }
});

这样问题就解决了。

列表中的每个子元素都应该有一个唯一的“key”道具。

通过在呈现元素中的key属性中声明index值来解决。

App.js组件

import Map1 from './Map1';

const arr = [1,2,3,4,5];

const App = () => {
  return (
    <>
     
     <Map1 numb={arr} />     

    </>
  )
}

export default App

Map.js组件

const Map1 = (props) => {

    let itemTwo = props.numb;
    let itemlist = itemTwo.map((item,index) => <li key={index}>{item}</li>)

    return (
        <>        
        <ul>
            <li style={liStyle}>{itemlist}</li>
        </ul>
        </>
    )
}

export default Map1