我得到以下错误,我明白它告诉我什么,但我不知道如何解决这个问题。
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;
当我将项目移回电子邮件列表时,问题发生了,一旦它们被移动到'draggedEmails'列表。
下面的代码是用来创建元素和键的。
createEmailItem(em) {
return React.createElement(
EmailItem, { email: em, key: `${em.id}` });
}
任何帮助都是感激的,
谢谢。
编辑:控制台。将一个条目从"email"列表移到"draggedEmails"列表后的记录状态。
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>
);
}
我找到问题了。
第一个错误是下面的代码返回'undefined'而不是'null'
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 });
所以总的来说,我错了很多…
感谢评论的人