javascript - 用反应删除数组中的元素,没有工作
问题描述
不工作,handleRemoveNote 功能 App 组件:
handleRemoveNote(id){
let{ notes } = this.state;
notes = notes.filter(function(note) {
return note.noteId !== id;
})
for (var i = 0; i < notes.length; i++) {
notes[i].noteId = i+1;
}
this.setState({ notes })
console.log(notes)
}
组件说明:
handleRemove(noteId){
this.props.removeNote(noteId);
}
调用 onClick
<span
onClick = {() => this.handleRemove(this.noteId)}
>
<i className="fas fa-trash-alt float-right"></i>
</span>
App 组件中笔记的渲染:
{
this.state.notes.map(note =>{
return(
<Note
removeNote = {this.handleRemoveNote}
noteId = {note.noteId}
noteContent= {note.noteContent}
/>
)
})
}
Note 组件的构造函数:
constructor(props){
super(props);
this.noteId = props.noteId;
this.noteContent = props.noteContent;
}
我不明白为什么它不起作用,它从列表中删除了最后一项,而不是我想要的,我做了一个“console.log(注释)”,它显示了正确删除元素的排列
解决方案
以下是链接提供的代码中的一些问题: 1. 在 map 中迭代时必须给出 key 属性
this.state.notes.map(note =>
<Note
removeNote = {this.handleRemoveNote}
noteId = {note.noteId}
noteContent= {note.noteContent}
key={note.noteId}
/>)
然后它应该从 Note render() 方法中删除
- 您实际上并不想在删除后重新分配密钥,您可能会从服务器获取这些 ID,因此您必须将它们用作密钥。这也是这里的主要问题
这样,您的新注释数组将不包含带有键的元素,该键是您最后一个元素的索引,因此它认为您要删除带有此键的元素 - 最后一个元素。只需删除该循环,一切都应该正常
for (var i = 0; i < notes.length; i++) {
notes[i].noteId = i+1;
}
推荐阅读
- python - 模型放置
- oop - 状态设计模式 - 当一个新状态添加到父状态时,这会导致另一个状态也发生变化,我们如何防止改变另一个状态
- sql - 如何在 SQL 中查找频率
- email - 电子邮件液体模板 - 拆分字符串并显示字符串 [index] 内联
- linux - 在 .text 部分分配可写内存
- gatsby - 盖茨比的 gitignore 中包含 public 是否有原因?
- environment-variables - 在 traefik2 中定义要在文件提供程序中使用的环境变量
- python - 来自图像 python 的下采样矩阵
- javascript - 动态导入图像时出错:“错误:找不到模块'./asset/
.jpg'" - vue.js - 如何禁用 Vuetify 的样式?