我收到以下错误,我明白它告诉我什么,但我无法弄清楚如何解决问题。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>
);
}
您是否尝试记录状态,并在尝试将其移回时,看看该项目是否仍在“draggedEmail”列表中? –
你在'render'方法中调用'createEmailItem'吗? –
我在我的文章中添加了记录状态,是的,我在我的渲染方法中调用以下内容。 {this.props.emails.map(此。createEmailItem)} – SkelDave