首页 > 解决方案 > 用反应删除数组中的元素,没有工作

问题描述

不工作,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(注释)”,它显示了正确删除元素的排列

标签: javascriptreactjs

解决方案


以下是链接提供的代码中的一些问题: 1. 在 map 中迭代时必须给出 key 属性

this.state.notes.map(note =>
<Note
removeNote = {this.handleRemoveNote}
noteId = {note.noteId}
noteContent= {note.noteContent}
key={note.noteId}
/>)

然后它应该从 Note render() 方法中删除

  1. 您实际上并不想在删除后重新分配密钥,您可能会从服务器获取这些 ID,因此您必须将它们用作密钥。这也是这里的主要问题

这样,您的新注释数组将不包含带有键的元素,该键是您最后一个元素的索引,因此它认为您要删除带有此键的元素 - 最后一个元素。只需删除该循环,一切都应该正常

for (var i = 0; i < notes.length; i++) {
    notes[i].noteId = i+1;
}

推荐阅读