N
N
NikFedoseev2018-07-03 20:05:22
JavaScript
NikFedoseev, 2018-07-03 20:05:22

How to correctly change the state of a component in React.js?

There is a component. A new note (an object with two fields "title", "text") is passed to this component through props. In the created note, a function is broadcast to the onClick event that passes the id through props to the parent component. The parent component stores an array of objects in states, that is, notes, the note id is equal to the object number in the array. When you try to delete a note, everything disappears. And the very first note which is under index 0 is not deleted. What could be the problem? Wrong state change?
When adding a note, I concatenate the old array and the new one. When deleting, I simply remove one object from the array.
5b3baafb44c11049941709.png5b3baccb3f2b0638911884.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-07-03
@NikFedoseev

Are you sure you understand how the splice method works ? Its call returns an array of removed elements, not the array from which those elements were removed.
Solution options:

handleNoteDel = index => {
  const notes = [...this.state.notes];
  notes.splice(index, 1);
  this.setState({ notes });
}

or:
handleNoteDel = index => {
  this.setState({
    notes: this.state.notes.filter((_, i) => i !== index),
  });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question