了解React.js中数组子项的唯一键

JavaScript

猿路易

2020-03-09

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

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

我的TableComponent渲染方法返回:

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

TableHeader组件是单行,并且还为其分配了唯一的键。

每个row输入rows都是通过具有唯一键的组件构建的:

<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>
    )
  }
});

是什么导致独特的按键道具错误?

第314篇《了解React.js中数组子项的唯一键》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
米亚小哥斯丁 2020.03.09

这是一个警告,但是解决此问题将使Reacts渲染速度更快

This is because React needs to uniquely identify each items in the list. Lets say if the state of an element of that list changes in Reacts Virtual DOM then React needs to figure out which element got changed and where in the DOM it needs to change so that browser DOM will be in sync with the Reacts Virtual DOM.

As a solution just introduce a key attribute to each li tag. This key should be a unique value to each element.

Green老丝Itachi 2020.03.09
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>
    )
  }
});

这样可以解决问题。

小哥卡卡西 2020.03.09

这可能对某人没有帮助,但可能是快速参考。这也与上面给出的所有答案相似。

我有很多使用以下结构生成列表的位置:

return (
    {myList.map(item => (
       <>
          <div class="some class"> 
             {item.someProperty} 
              ....
          </div>
       </>
     )}
 )

经过一番尝试和错误(和一些挫折)后,将键属性添加到最外层的块即可解决该问题。另请注意,<>标记现在已被标记替换。

return (

    {myList.map((item, index) => (
       <div key={index}>
          <div class="some class"> 
             {item.someProperty} 
              ....
          </div>
       </div>
     )}
 )

当然,在上面的示例中,我一直很天真地使用迭代索引(索引)填充键值。理想情况下,您将使用列表项特有的内容。

Tom老丝 2020.03.09

在react中定义唯一键的最佳解决方案:在地图内初始化名称后,然后按key = {post.id}定义键,或者在我的代码中看到我定义了名称项,然后按key = {item.id定义键}:

<div className="container">
                {posts.map(item =>(

                    <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="card-text">{item.email}</p>
                    </div>
                  </div>
                ))}
            </div>

猿EvaL 2020.03.09

检查:键= undef !!!

您还会收到警告消息:

Each child in a list should have a unique "key" prop.

如果您的代码是完整的正确的,但是如果

<ObjectRow key={someValue} />

someValue未定义!!!请先检查一下。您可以节省时间。

樱A 2020.03.09

警告:数组或迭代器中的每个子代都应具有唯一的“键”道具。

这是一个警告,因为要迭代的数组项将需要独特的相似之处。

React将迭代的组件渲染处理为数组。

解决此问题的更好方法是在要迭代的数组项上提供索引,例如:

class UsersState extends Component
    {
        state = {
            users: [
                {name:"shashank", age:20},
                {name:"vardan", age:30},
                {name:"somya", age:40}
            ]
        }
    render()
        {
            return(
                    <div>
                        {
                            this.state.users.map((user, index)=>{
                                return <UserState key={index} age={user.age}>{user.name}</UserState>
                            })
                        }
                    </div>
                )
        }

索引是React内置的道具。

TomGil村村 2020.03.09

只需将唯一键添加到您的组件中

data.map((marker)=>{
    return(
        <YourComponents 
            key={data.id}     // <----- unique key
        />
    );
})

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android