映射警告时react唯一键

IT技术 node.js reactjs key mapping ejs
2021-05-01 23:57:17

我对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"
    }
  ]
}

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

谢谢您的帮助!:)

3个回答

我可以想到两种解决方法...

第一种方法是将键添加到周围的 div 而不是直接添加到ContestPreview元素上。

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

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

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

将包装器用于渲染每个对象的属性。

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

在您的代码中

<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(key)。我认为出于某种原因,在您的对象数组中,您有一个具有相同键的对象。

这样当您看到 console.log() 结果时。您将知道您的对象中出现错误的位置。

我希望这有助于您调试错误。