list items are not deleting properly (React)

前端 未结 1 1564
刺人心
刺人心 2020-12-02 03:05

I\'d appreciate some help with my note taking app. Let\'s say I have 3 notes on my notes list. I want to delete the note at the top of the list. No matter which one I try to

1条回答
  •  佛祖请我去吃肉
    2020-12-02 03:41

    This error is occurring from using index as your key. React uses the key attribute to track the elements inside the list. When you are deleting an element from the middle in an array, the index does not delete itself, instead it rearranges and the last index disappears. This is why the last element in your array always got deleted.

    For this solution, I have provided title of the note as the key, but this may not be always unique. You will be better using a generated key or a combination of fields as key

    class NoteEntry extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          display: false,
          editing: false,
          editTitle: this.props.title,
          editDetails: this.props.details
        }
        this.displayToggle = this.displayToggle.bind(this);
        this.edit = this.edit.bind(this);
        this.save = this.save.bind(this);
      }
    
      displayToggle() {
        this.setState(prevState => ({
          display: !prevState.display
        }))
      }
    
      edit() {
        this.setState({
          editing: true
        })
      }
    
      save() {
        let titleVal = this.refs.updateTitle.value;
        let detailsVal = this.refs.updateDetails.value;
        this.setState({
          editTitle: titleVal,
          editDetails: detailsVal,
          editing: false
        })
      }
    
      render() {
        return (
          
    {this.state.editing ? ( ) : (

    {this.state.editTitle}

    )}

    {this.displayTime}


    {this.state.editing ? ( ) : (

    {this.state.editDetails}

    )}
    {this.state.editing ? ( ) : ( ) }
    ) } } const NoteForm = (props) => { return (