简体   繁体   中英

What is the proper way to delete a React element?

I have a list, and I need to delete an element to be deleted.

The delete button works in that it sends the delete request to the server. However, a page refresh is needed to have it delete from the front end.

I want it deleted after the delete button is clicked.

I could simply set a boolean on the front end as follows:

render && <ComponentToDelete />

and change render from true to false .

Is this the preferred way or is there a best practice or more standard way.

I'm simply doing a delete on an item as part of CRUD operations.

I'm not sure if this is relevant:

https://reactjs.org/docs/react-dom.html#unmountcomponentatnode

Also, per comment here is how the list is generated:

    let render;
    if(new_articles.length > 1){
      render = new_articles.map((val, index) => {
        return <ComponentArticle key={index} data={val}/>;
      });            
    }
    return render;   

google search here

As in example above, you just need to remove item from new_articles . Let's say the deleted id is deleted_id, You can remove that item from array by trying the following snippet

new_articles.filter((article) => article_id !== deleted_id);

You should be using new_articles array as state value.

If you make any change to the array, render will update UI automatically.

So after you send delete request to server and get successful response, you can change the new_articles array to reflect the deleting.

You can use one of Javascript functions like fliter or splice with deleted index.

You have the data or metadata for you articles stored in an array as you are using map to create the finished article for rendering.

If you simply have React local state or Redux track this data, then it will handle the updating of the DOM for you using React's built in virtual DOM.

This is the primary benefit of using React is that you modify the state and React will update the UI for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM