我对react很陌生,我正面临一个我无法解决的问题。这是我的react组件:
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;
此代码给了我以下警告:
警告:数组或迭代器中的每个孩子都应该有一个唯一的“键”props。检查 的渲染方法
App。有关更多信息,请参阅 HERE-FB-URL-I-REMOVED。在 App 中的 ContestPreview(由 App 创建)中
我完全理解这个错误意味着什么。我知道数组的每个元素在循环时都应该有一个唯一的键。我不明白的是为什么我会收到错误消息,因为在我的意见中,密钥应该用我的<ContestPreview key={contest.id} {...contest} />...来定义,这key={contest.id}还不够吗?
这是我的比赛数据:
{
"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"
}
]
}
在我看来,它应该可以工作,我不明白为什么我仍然收到此错误。我真的很想在我的问题上得到一些帮助,如果有人能解释我这里发生了什么,那真的很酷,因为我真的试图了解它是如何工作的。
谢谢您的帮助!:)