问题描述
我是一个很新的反应者,我面临着一个我无法解决的问题.这是我的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;
此代码给我以下警告:
我完全理解此错误的含义.我知道,数组中的每个元素在循环通过它们时都应具有唯一的键.我不明白为什么会出现此错误,因为在我的选择中,密钥应该用<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>
这篇关于映射警告时反应唯一键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!