javascript - 从对象数组中动态删除项目
问题描述
单击“删除”按钮后,如何从数组中动态删除对象。
例如,在下面的代码中,表格有 n 行。单击特定的删除按钮后,它应该只删除该行。就像一个待办事项列表。
但在我的情况下,整个表都被删除了。
const [items,itemList]=useState([]);
const [companyName,setCompanyName]=useState('');
const [experience, setExperience]=useState();
//Adding Items to Array after clicking "Add" button
const handleClose=()=>{
itemList((old)=>{
return [...old,{companyName,experience}]
})
}
//Removing Items from Array After clicking Remove button
const removeItem=(index)=>{
itemList((old)=>{
return old.filter((arrEle,i)=>{
return (
i!==index
);
})
})
}
//Displaying Array of objects on UI
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>Company Name</th>
<th>Experience</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
items.map((item,index)=>{
return(
<tr>
<td>{item.companyName}</td>
<td>{item.experience}</td>
<td><button onClick={()=>{removeItem(index)}}>Remove</button></td>
</tr>
)
})
}
</tbody>
</Table>
解决方案
问题
您的代码中的主要问题是您在表单中呈现了一堆按钮,并且几乎所有按钮都没有指定按钮类型。按钮的默认值为type="submit"
,因此当单击其中任何一个时,它们正在提交表单,并且表单正在执行默认的提交操作,这也恰好会重新加载页面。当页面重新加载时,您的应用会重新加载并丢失本地组件状态。
按钮类型属性
按钮的默认行为。可能的值为:
submit
:按钮将表单数据提交给服务器。如果没有为与 a 关联的按钮指定属性<form>
,或者该属性为空值或无效值,则这是默认值。reset
:该按钮将所有控件重置为其初始值,例如<input type="reset">
。(这种行为往往会惹恼用户。)button
:按钮没有默认行为,默认按下时什么也不做。它可以让客户端脚本监听元素的事件,这些事件在事件发生时触发。
解决方案
明确指定按钮类型。
删除按钮
<button type="button" // <-- "button" type onClick={() => { removeItem(item); }} > Remove </button>
提交、重置和打开模式的表单按钮
<Button variant="primary" type="submit"> <-- "submit" type Submit </Button> <Button variant="primary" type="reset" // <-- "reset" type style={{ margin: '0 20px' }} > Reset Form </Button> <Button variant="primary" type="button" // <-- "button" type onClick={handleShow} style={{ margin: '0 15px' }} > Add Experience </Button>
注意:提交按钮仍将提交表单,并且由于您没有onSubmit
对组件进行任何回调,因此Form
该按钮将导致页面重新加载。您将需要添加一个提交处理程序并调用preventDefault
事件onSubmit
对象。
const submitHandler = e => {
e.preventDefault();
// handle form data or whatever
};
...
<Form onSubmit={submitHandler}>
...
推荐阅读
- python - PyTorch 等效于 index_add_ 取而代之的是最大值
- minitest - 如何存根接受和参数的方法
- python - scrapy没有跟随链接没有错误
- java - 缺少有关 Jenkins 的测试分析器报告
- jquery - addClass 函数没有按预期工作
- javascript - npx 和 npm 的区别?
- javascript - 如何在输入文本中设置唯一可能的值
- php - 使用 jquery/bootstrap,不使用复选框保存数据
- javascript - 检查对象数组是否包含具有特定属性名称的特定值
- javascript - 荣誉中具有复杂条件的javascript过滤器