2017-09-26 44 views
1

我很新,反应并且我遇到了一个我无法解决的问题。这里是我的反应成分:当映射警告时反应唯一键码

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的渲染方法。有关更多信息,请参阅 HERE-FB-URL-I-REMOVED。 在ContestPreview(由应用程序创建) 在应用

我完全理解了这个错误表示。我知道数组中的每个元素在循环时都应该有一个唯一的键。我不明白的是为什么我得到的错误,因为在我opionion的关键应该与我的<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" 
    } 
    ] 
} 

在我opionion它应该工作,我不明白为什么我仍然得到这个错误。我真的想在我的问题上得到一些帮助,如果有人能够解释我发生了什么事情,那真的很酷,因为我真的试图了解它是如何工作的。

谢谢你的帮助! :)

+0

您可以检查在任何时间点数据是否变得未定义或为空 –

+0

有没有任何答案可以帮助您解决问题? –

+0

@ spencer.sm不,但我自己解决了。我重新启动了整个服务器,仍然是一样的。所以我有点生气,决定关闭我的电脑一个小时。重启后,它完美运行。不知道它是什么,认为有些东西没有被正确地诠释。 – Twinfriends

回答

-1

在你的代码在这里

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

这将控制台每个组件的ID(键),你是在你的地图绘制。我认为出于某种原因,在你的对象数组中你有一个具有相同键的对象。

这样当你看到console.log()结果。你会知道你的对象在哪里有错误。

我希望这可以帮助您调试错误。

0

将包装器渲染为呈现每个对象的属性。

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

我能想到的两种解决方法的......

第一种方式将是关键,直接添加到周围的DIV而不是ContestPreview元素。

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

第二种方法是修改ContestPreview,使其实际使用key道具。

render(){ 
    <div key={this.props.key}> 
    ... 
    </div> 
}