javascript - array.splice(index, 1) 返回删除项目的数组
问题描述
我正在学习反应钩子,我只是想做一个简单的功能来从列表中删除项目。为此,我使用了 find、indexOf 和 splice。
在 onClick 函数中,我在 array.splice(indexOf, 1) 中使用 indexOf,但它只返回列表中的项目。一切都会重新渲染并执行它应该做的事情,但唯一渲染的项目是我刚刚尝试删除的项目。我错过了什么?
const [todos, setToDo] = useState(initialToDo);
const [input, setInput] = useState('');
const todoList = (todos) => {
return (
todos.map((todo) => {
return (
<div className='todo-list flex p-2 w-1/2 justify-between'>
<p className="px-3">{todo.name}</p>
<button
className='rounded-sm border-2 px-2'
onClick={(e)=>{
let item = todos.find(el=>el.id == todo.id);
console.log(item)
let index = todos.indexOf(item);
console.log(index)
todos = todos.splice(index, 1)
// todos == item
setToDo(todos)
}}
>-</button>
</div>
)}))
}
解决方案
是的,Array.splice
返回删除的元素并改变原始数组,这意味着您可以使用index
从todos
列表中删除/更新待办事项。
执行此操作的最简单方法是以下方式。这是工作示例
const todoList = () => {
const [todos, setToDo] = useState(initialToDo);
const [input, setInput] = useState('');
const handleDelete = index => {
todos.splice(index, 1)
setToDo([...todos])
}
return (
todos.map((todo, index) => {
return (
<div className='todo-list flex p-2 w-1/2 justify-between'>
<p className="px-3">{todo.name}</p>
<button
className='rounded-sm border-2 px-2'
onClick={() => handleDelete(index)}
>
-
</button>
</div>
)}))
}
推荐阅读
- python - 如何在我的注册表中添加名字和姓氏
- javascript - 为什么我的搜索没有检查所有标签元素?引导程序,JS
- php - 如何同时使用 $dates 数组和 Factory
- android - Kotlin Room Database - 如何对列执行求和查询?
- javascript - javascript 函数是否与使用的引导程序版本密切相关?
- angular - 具有入口的 Kubernetes 上 Angular 应用程序的重定向问题
- python - 当没有缩进问题时,JupyterLab 不断给出 else 的语法错误
- vue.js - 如何在 VueJs APP 中从 JWT 更新用户信息而不重新登录
- gitlab - 通过 CI/CD 管道运行时,Terraform 忽略 S3 中的后端状态存储
- javascript - 登录并销毁多个机器人