【问题标题】:React Duplicate Key Error反应重复键错误
【发布时间】:2016-06-28 08:28:07
【问题描述】:

我收到以下错误,我明白它告诉我的内容,但我不知道如何解决这个问题。

flattenChildren(...): Encountered two children with the same key...

我的页面上有 2 个包含电子邮件的列表。我的应用的初始状态包含以下数据:

const initialState = {

  emails: [
    {
      id: 1, from: 'test.1@test.co.uk', body: 'test1 body', title: 'test 1 title',
    },
    {
      id: 2, from: 'test.2@test.co.uk', body: 'test2 body', title: 'test 2 title',
    },
  ],

  draggedEmails: [],

};

我的应用程序的 UI 允许您将项目从第一个列表(电子邮件)拖放到第二个列表(draggedEmails)。

在我的 Redux reducer 中,我有以下代码可以在列表之间移动电子邮件。

  let newState = {};

  //Check if the email exists in my 'emails' array
  const doesExistInEmails = state.emails.find(x => x.id === action.id) !== null;

  //If it exists then move it to the 'draggedEmails' list
  if (doesExistInEmails) {

    const filteredEmails = state.emails.filter(e => e.id !== action.emailItem.id);

    newState = Object.assign(
      {},
      state,
      { draggedEmails: [...state.draggedEmails, action.emailItem], emails: filteredEmails }
      );

  } else {

    const filteredEmails = state.emails.filter(e => e.id !== action.emailItem.id);

    newState = Object.assign(
      {},
      state,
      { draggedEmails: [...state.emails, action.emailItem], emails: filteredEmails });
  }

  return newState;

当我将项目移回电子邮件列表时会出现问题,一旦它们被移动到“dragedEmails”列表。

以下代码用于创建元素和键。

createEmailItem(em) {
    return React.createElement(
      EmailItem, { email: em, key: `${em.id}` });
 }

感谢您的帮助,

谢谢。

编辑:将一项从“电子邮件”列表移动到“拖动电子邮件”列表后的 Console.Logged 状态。一切看起来都应该如此。

Object {emails: Array[1], draggedEmails: Array[1]}

EDIT2:添加渲染方法。

render() {
    return (
    <div className="email-container" onDrop={this.onDrop} onDragOver={this.allowDrop}>
          {this.props.emails.map(this.createEmailItem)}
    </div>
    );
}

【问题讨论】:

  • 您是否尝试过记录状态并在您尝试将其移回时查看该项目是否仍在“dragedEmail”列表中?
  • 你是在render方法中调用createEmailItem吗?
  • 我已经在我的帖子中添加了记录状态,是的,我在我的渲染方法中调用了以下内容。 {this.props.emails.map(this.createEmailItem)}
  • 检查数组是否有重复的 ids

标签: reactjs ecmascript-6 redux


【解决方案1】:

我发现了问题。有4个。

首先是下面的返回'undefined'而不是'null'

const doesExistInEmails = state.emails.find(x => x.id === action.id) !== null;

第二个是我的action没有id,我的action有一个有id的emailItem

const doesExistInEmails = state.emails.find(x => x.id === action.emailItem.id) !== undefined;

第三个是我在过滤我的电子邮件,而不是在下一行拖动电子邮件。

const filteredEmails = state.filter(e => e.id !== action.emailItem.id);

最后我在设置状态时分配了错误的值。

{ draggedEmails: [...state.emails, action.emailItem], emails: filteredEmails });

应该是……

{ emails: [...state.emails, action.emailItem], draggedEmails: filteredEmails });

所以总的来说,我错了很多......

感谢评论的人。

【讨论】:

  • 很高兴你解决了这个问题。如果您还没有,我建议您使用react-logger
猜你喜欢
  • 2018-10-29
  • 2020-02-15
  • 1970-01-01
  • 2011-10-17
  • 2012-03-03
  • 2018-08-26
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多