[英]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 .并将
render
从true更改为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.我只是在作为 CRUD 操作的一部分对项目进行删除。
I'm not sure if this is relevant:我不确定这是否相关:
https://reactjs.org/docs/react-dom.html#unmountcomponentatnode 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;
As in example above, you just need to remove item from new_articles
.如上例所示,您只需要从
new_articles
删除 item 。 Let's say the deleted id is deleted_id, You can remove that item from array by trying the following snippet假设删除的 id 是 delete_id,您可以通过尝试以下代码段从数组中删除该项目
new_articles.filter((article) => article_id !== deleted_id);
You should be using new_articles
array as state value.您应该使用
new_articles
数组作为状态值。
If you make any change to the array, render will update UI automatically.如果对数组进行任何更改,render 将自动更新 UI。
So after you send delete request to server and get successful response, you can change the new_articles
array to reflect the deleting.因此,在您向服务器发送删除请求并获得成功响应后,您可以更改
new_articles
数组以反映删除。
You can use one of Javascript functions like fliter
or splice
with deleted index.您可以使用 Javascript 函数之一,如带有删除索引的
fliter
或splice
。
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.当您使用 map 创建用于渲染的成品文章时,您将文章的数据或元数据存储在一个数组中。
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.如果您只是让 React 本地状态或 Redux 跟踪这些数据,那么它将使用 React 内置的虚拟 DOM 为您处理 DOM 的更新。
This is the primary benefit of using React is that you modify the state and React will update the UI for you.这是使用 React 的主要好处是你修改状态,React 会为你更新 UI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.