反应:如何在不使用唯一 ID 的情况下删除它?
REACT: How can I delete this without using unique id?
我想使用或不使用唯一键删除此 TODO
这是HOOK代码
const [todos, setTodos] = useState([{}])
const [user, setUser] = useState({
id: uuidv4(),
name: '',
email: '',
phone: '',
})
This one is the Function to set Input and delete a todo
const addTodo = (e) => {
e.preventDefault()
setTodos([...todos, user])
console.log(addTodo)
}
console.log(user)
const delTodo = (e, id) => {
e.preventDefault()
console.log(id)
todos.splice(id, 1)
setTodos([...todos])
}
Here These are being mapped
{todos.map((todo) => (
<div>
<li key={todo.id}>
{todo.name}, {todo.email}, {todo.phone}
</li>
<button onClick={delTodo} color='danger'>
Delete
</button>
</div>
))}
This is what i get when i console.log
link to image
更新您的 delTodo
函数,如下所示。
splice 使用第一个参数作为要删除的数组中的 start index
,第二个参数是 deleteCount
。因此,在您的情况下,您需要获得 object
.
的 index
您可以用 indexOf() 获得 object
的 index
。它将return -1
of object
不属于那个数组。所以添加 if (index != -1) { }
然后你可以在里面使用 todos.splice(index, 1);
.
const delTodo = (e, id) => {
e.preventDefault();
console.log(id);
let index = todos.indexOf(id);
if (index != -1) {
todos.splice(index, 1);
}
setTodos([...todos]);
}
我想使用或不使用唯一键删除此 TODO
这是HOOK代码
const [todos, setTodos] = useState([{}])
const [user, setUser] = useState({
id: uuidv4(),
name: '',
email: '',
phone: '',
})
This one is the Function to set Input and delete a todo
const addTodo = (e) => {
e.preventDefault()
setTodos([...todos, user])
console.log(addTodo)
}
console.log(user)
const delTodo = (e, id) => {
e.preventDefault()
console.log(id)
todos.splice(id, 1)
setTodos([...todos])
}
Here These are being mapped
{todos.map((todo) => (
<div>
<li key={todo.id}>
{todo.name}, {todo.email}, {todo.phone}
</li>
<button onClick={delTodo} color='danger'>
Delete
</button>
</div>
))}
This is what i get when i console.log
link to image
更新您的 delTodo
函数,如下所示。
splice 使用第一个参数作为要删除的数组中的 start index
,第二个参数是 deleteCount
。因此,在您的情况下,您需要获得 object
.
index
您可以用 indexOf() 获得 object
的 index
。它将return -1
of object
不属于那个数组。所以添加 if (index != -1) { }
然后你可以在里面使用 todos.splice(index, 1);
.
const delTodo = (e, id) => {
e.preventDefault();
console.log(id);
let index = todos.indexOf(id);
if (index != -1) {
todos.splice(index, 1);
}
setTodos([...todos]);
}