即使已设置密钥,也可以在React中获取密钥道具警告 [英] Getting key prop warning in React, even though key is set

查看:62
本文介绍了即使已设置密钥,也可以在React中获取密钥道具警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此警告:

警告:数组或迭代器中的每个子代均应具有唯一的键"道具.检查EventsTable的呈现方法.请参阅 fb.me/react-warning-keys 更多信息.

react-runtime-dev.js?8fefd85d334323f8baa58410bac59b2a7f426ea7:21998警告:数组或迭代器中的每个子代都应具有唯一的密钥"属性.检查事件的渲染方法.请参阅 fb.me/react-warning-keys 更多信息.

react-runtime-dev.js?8fefd85d334323f8baa58410bac59b2a7f426ea7:21998 Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of Event. See fb.me/react-warning-keys for more information.

来源

这是 EventsTable :

EventsTable = React.createClass({
  displayName: 'EventsTable',

  render() {
    console.dir(this.props.list);

    return (
      <table className="events-table">
        <thead>
          <tr>
            {_.keys(this.props.list[0]).map(function (key) {
              if (key !== 'attributes') {
                return <th>{key}</th>;
              }
            })}
         </tr>
        </thead>

        <tbody>
          {this.props.list.map(function (row) {
            return (
              <Event key={row.WhatId} data={row} />
            );
          })}
        </tbody>
      </table>
    )
  }
});

这是事件:

Event = React.createClass({
  displayName: 'Event',

  render() {
    return (
      <tr>
        {_.keys(this.props.data).map((x) => {
          if (x !== 'attributes')
            return <td>{this.props.data[x]}</td>;
        })}
      </tr>
    )
  }
});

问题

很明显,我在< Event/> 组件上具有了 key 道具.我遵循的惯例是,您应该在组件上包括 key ,而不是在HTML本身上(换句话说,在 Event 组件内的HTML标签).根据官方的React文档:

Question

Clearly I've got the key prop on the <Event /> component. And I'm following the convention that you're supposed to include key on the component, not on the HTML itself (in other words, HTML tags within the Event component). Per the official React docs:

密钥应始终直接提供给数组中的组件,而不是数组中每个组件的容器HTML子代:

The key should always be supplied directly to the components in the array, not to the container HTML child of each component in the array:

我很困惑.为什么我会收到警告?

I'm severely confused. Why am I getting warnings?

推荐答案

您是否尝试过将 key 添加到< th> 标记?

Have you tried adding a key to the <th> tag?

         <tr>
            {_.keys(this.props.list[0]).map(function (key) {
              if (key !== 'attributes') {
                return <th key={key}>{key}</th>;
              }
            })}
         </tr>

这篇关于即使已设置密钥,也可以在React中获取密钥道具警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆