Javascript 使用react移除阵列中的元素,不工作

Javascript 使用react移除阵列中的元素,不工作,javascript,reactjs,Javascript,Reactjs,无法工作,handleRemoveNote功能应用程序组件: 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;

无法工作,handleRemoveNote功能应用程序组件:

  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)
  }
      {
        this.state.notes.map(note =>{
        return(
          <Note
            removeNote = {this.handleRemoveNote}
            noteId = {note.noteId}
            noteContent= {note.noteContent}
            />
        )
        })
      }
  constructor(props){
    super(props);
    this.noteId = props.noteId;
    this.noteContent = props.noteContent;
  }
呼叫onClick

 <span
     onClick = {() => this.handleRemove(this.noteId)}
     >
     <i className="fas fa-trash-alt float-right"></i>
 </span>
  • 应用程序组件:
  • 注:组成部分:

我不明白为什么它不起作用,它从列表中删除了最后一项,而不是我想要的,我制作了一个“console.log(notes)”,它向我展示了正确删除元素的安排 1.在映射中迭代时,必须给出key属性

this.state.notes.map(note =>
<Note
removeNote = {this.handleRemoveNote}
noteId = {note.noteId}
noteContent= {note.noteContent}
key={note.noteId}
/>)
this.state.notes.map(note=>
)
然后它应该从Note render()方法中删除

  • 在删除后,您实际上不想重新分配密钥,您可能会从服务器获得这些ID,因此您必须将它们用作密钥。这也是这里的主要问题
  • 这样,新的notes数组将不包含带有键的元素,键是最后一个元素的索引,因此它认为您希望删除带有此键的元素,即最后一个元素。只要去掉这个循环,一切都会好起来的

    for (var i = 0; i < notes.length; i++) {
        notes[i].noteId = i+1;
    }
    
    for(变量i=0;i
    不是解决方案,但请记住为地图中的每个注释添加关键参数。我认为问题在于
    this.noteId
    ,是不是应该是
    this.props.noteId
    (在onClick内部)?应该是this.handleRemove(this.props.noteId)}?
    构造函数(props){super(props);this.noteId=props.noteId;this.noteContent=props.noteContent;}
    Note的构造函数component@Alvaro好,代码链接准备键的重新排序是因为当您删除注释时,例如我有注释1、注释2和注释3,如果您删除了注释2并添加了一个新注释,则有两个注释具有相同的键3当您可能需要使用其他内容作为元素的键时,您不能依赖您将从ui提供的ID,用于键的ID必须是唯一的,可能的解决方案:1)您使用一些内部ID作为键,它们对于所有注释都是唯一的,您可以使用类似于2)不要从ui输入ID并在内部分配它们,确保它们始终是唯一的+删除重新排序代码。
    for (var i = 0; i < notes.length; i++) {
        notes[i].noteId = i+1;
    }