映射警告时反应唯一键 [英] React unique key when mapping warning

查看:68
本文介绍了映射警告时反应唯一键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个很新的反应者,我面临着一个我无法解决的问题.这是我的react组件:

I'm quite new to react and I'm facing a problem I can't solve. Here is my react component:

import React from 'react';
import Header from './Header';
import ContestPreview from './ContestPreview';

class App extends React.Component {

    state = { 
        pageHeader: 'Naming Contests',
        whatever: 'test'
    };

    render() {
        return (
            <div className="App">
                <Header message={this.state.pageHeader} />
                <div>
                    {this.props.contests.map(contest =>
                        <ContestPreview key={contest.id} {...contest} />
                    )}
                </div>
            </div>
        );
    }
}

export default App;

此代码给我以下警告:

警告:数组或迭代器中的每个子代均应具有唯一的键" 支柱.检查App的渲染方法.看 有关更多信息,请点击此处FB-URL-I-已删除. 在ContestPreview中(由App创建) 在应用程序中

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of App. See HERE-FB-URL-I-REMOVED for more information. in ContestPreview (created by App) in App

我完全理解此错误的含义.我知道,数组中的每个元素在循环通过它们时都应具有唯一的键.我不明白为什么会出现此错误,因为在我的选择中,密钥应该用<ContestPreview key={contest.id} {...contest} />定义... ... key={contest.id}还不够吗?

I totally understand what this error means. I understand that each element of an array should have a unique key when looping trough them. What I don't understand is why I get the error, since in my opionion the key should be defined with my <ContestPreview key={contest.id} {...contest} /> ... is key={contest.id} not enough?

这是我的比赛数据:

{
  "contests": [
    {
      "id": 1,
      "categoryName": "Business/Company",
      "contestName": "Cognitive Building Bricks"
    },
    {
      "id": 2,
      "categoryName": "Magazine/Newsletter",
      "contestName": "Educating people about sustainable food production"
    },
    {
      "id": 3,
      "categoryName": "Software Component",
      "contestName": "Big Data Analytics for Cash Circulation"
    },
    {
      "id": 4,
      "categoryName": "Website",
      "contestName": "Free programming books"
    }
  ]
}

以我的观点,它应该可以工作,我不明白为什么我仍然会收到此错误.我真的很想获得有关我的问题的帮助,如果有人可以向我解释一下这里发生的事情,那真是太酷了,因为我真的试图了解它的工作原理.

In my opionion it should work, I can't understand why I still get this error. I would really like to get some help on my problem, it would be really cool if someone can explain me whats going on here since I really try to understand how it works.

谢谢您的帮助! :)

推荐答案

将包装器放置为呈现每个对象的属性.

Put wrapper to rendering of each object's properties.

<div>
    {this.props.contests.map(contest =>
        <div key={contest.id}>
             <ContestPreview {...contest} />
        </div>
    )}
</div>

这篇关于映射警告时反应唯一键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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