2016-06-28 105 views
0

我收到以下错误,我明白它告诉我什么,但我无法弄清楚如何解决问题。React Duplicate Key Error

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

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

const initialState = { 

    emails: [ 
    { 
     id: 1, from: '[email protected]', body: 'test1 body', title: 'test 1 title', 
    }, 
    { 
     id: 2, from: '[email protected]', 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; 

当我将项目移回到“draggedEmails”列表后,将项目移回到电子邮件列表时,会出现问题。

下面的代码是用来创建元素和键的。

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

任何帮助表示赞赏,

感谢。

编辑:将一个项目从'emails'列表移动到'draggedEmails'列表后编辑:Console.Logged状态。一切都看起来应该如此。

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

编辑2:添加渲染方法。

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

您是否尝试记录状态,并在尝试将其移回时,看看该项目是否仍在“draggedEmail”列表中? –

+0

你在'render'方法中调用'createEmailItem'吗? –

+0

我在我的文章中添加了记录状态,是的,我在我的渲染方法中调用以下内容。 {this.props.emails.map(此。createEmailItem)} – SkelDave

回答

1

我发现了这个问题。有4

第一,其次为回报“不确定”,而不是“空”

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

第二个是我的动作没有一个ID,我的动作有emailItem这有一个id

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 }); 

所以,总体来说,我有很多错误的...

感谢谁评论的家伙。

+0

快乐你的工作。我可以建议如果你还没有使用['react-logger'](https://www.npmjs.com/package/redux-logger)。 –