反应错误index.js:1452警告:数组或迭代器中的每个子代都应具有唯一的“键”属性

时间:2018-11-30 21:52:05

标签: javascript reactjs mobx

我正在尝试在React中使用Mobx遍历商店。这是我的contact.jsx。

import React, { Component } from 'react';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import Jumbotron from '../components/Jumbotron';
import {inject, observer} from 'mobx-react';

@inject('MemberStore')
@observer

class Contact extends Component {
 handleSubmit = (e) => {
    e.preventDefault();

    const member = this.member.value;
    const email = this.email.value;
    // const email = this.email.value;
    this.props.MemberStore.addMember({member, email});
    this.member.value = '';
    this.email.value = '';
}
render() {
    const {MemberStore} = this.props;

    return (
        <div>
            <Navbar />
            <Jumbotron title="Contact Page" subtitle="You want to get in touch"/>
            <div className="container">
               <h2>You have {MemberStore.memberCount} members.</h2>

               <form onSubmit={e => this.handleSubmit(e)}>
                   <input type="text" placeholder="Enter Your Name" ref={input => this.member = input }/>
                   <div>
                   <input type="text" placeholder= "Enter Your Email" ref={input => this.email = input }/>
                   </div>
                   <button>Submit</button>
               </form>
               <ul>
                {MemberStore.members.map(({member, email}) => (
                    <li key={member}>
                        {member}
                        {email}
                    </li>
                ))}
                </ul>
            </div>
            <Footer />
        </div>
    )
  }
 }   

导出默认联系人;

现在它只返回电子邮件,并且出现以下错误。

index.js:1452 Warning: Each child in an array or iterator should have a unique "key" prop.

但是我没有将其包含在地图功能中吗?任何帮助,将不胜感激。 下面是我的会员商店的代码。

import {observable, action, computed} from 'mobx';

class MemberStore {
@observable members = [];

@action addMember({name, email}) {
    const existing = this.members;
    this.members = existing.concat({name,email});
}

@computed get memberCount() {
    return this.members.length;
 }

}
const store = new MemberStore();
export default store;

2 个答案:

答案 0 :(得分:1)

您的members数组存储项具有两个属性:nameemail。 在地图函数中,您正在使用解构({member, email})member项目中没有members属性。将member更改为name(如果要将每个项目用作键,请确保每个项目的name属性都具有唯一值)。

  <ul>
    {MemberStore.members.map(({ name, email }, i) => (
      <li key={i}>
        {name}
        {email}
      </li>
    ))}
  </ul>

答案 1 :(得分:0)

我不知道member中会出现什么,它永远都应该是相同的,所以尝试一下:

<ul>
  {MemberStore.members.map(({member, email}, index) => (
     <li key={index}>
        {member}
        {email}
     </li>
  ))}
</ul>