There is an array comments with a list of comments that users have entered into the form. With the help of filter, on click on the "Delete" button, I iterate through this array, leaving elements that are not equal to ID. I collect the elements in a new array newListItem. If I understand correctly, React will not draw a new list, since the old one has remained unchanged.

The current code is here: https://codepen.io/iliyasold/pen/oNoZKov

The question is: how to transfer the data of the new array newListItem to state?

I tried to change the state by adding to the functionremoveCommentItem const [items, setItems]= useState([]);and thensetItems(newListItem), but nothing comes out. In addition, initialstate is not empty already, since there are elements in the list. How to write it all down? What is the principle here? Thanks to.

Is the project on GitHub? The code of this component and parent is necessary. I ran into a very similar problem this week. In short, 1) copying objects through "="does not create a copy, but a link to the original object. (in this case, on props) 2) functional components do not track "in depth" what is happening inside the object in state. As a result, I had state changes, but without re-rendering.

Iurii2022-02-12 21:18:15

Yes, there is, uploaded here: github.com/iliyasold/commentsWidget

Iliya V. Soldatkin2022-02-12 21:18:15
  • Answer # 1
    const {comments}= props;

    Your example shows that comments come from props, and props cannot be changed. So you need to push the new list of comments higher into the parent and where comments are initially stored there already and change const [items, setItems]= useState([]) and React will render and display the new comments.

    Okay, but how exactly do you do it? How to "throw" it?

    Iliya V. Soldatkin2022-02-12 21:18:15

    Pass the saveComment(comments) function through props to your commentlist component (as well as removeItem from the CommentItem component by analogy) and already call this function in the removeCommentItem function. And there is already something like this saveComment(commects) { setItems(commects) }, but this will happen in the commentlist parent.

    Enokin2022-02-12 21:18:15

    Ah, that is, you mean that the function itself, which removes the element, should be moved higher, right?

    Iliya V. Soldatkin2022-02-12 21:18:15

    Yes, you can. And save the new array with comments into a variable that is passed to commentList via props. But in order for Reax to rebuild, you need to do it through the useState hooks, for example

    Enokin2022-02-12 21:18:15

    Ok, I'll try, thanks.

    Iliya V. Soldatkin2022-02-12 21:18:15