[英]array.splice(index, 1) returns array with removed item
I am learning react hooks and I am just trying to do a simple function to remove the item from the list.我正在学习反应钩子,我只是想做一个简单的 function 从列表中删除该项目。 To do this I am using find, indexOf, and splice.
为此,我使用了 find、indexOf 和 splice。
In the onClick function, I am using the indexOf in the array.splice(indexOf, 1), BUT it returns just the item from the list.在 onClick function 中,我在 array.splice(indexOf, 1) 中使用 indexOf,但它只返回列表中的项目。 Everything rerenders and does what it is supposed to do, but the only itme that renders is the item that I just tried to delete.
一切都会重新渲染并执行它应该做的事情,但唯一渲染的项目是我刚刚尝试删除的项目。 What am I missing?
我错过了什么?
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>
)}))
}
Yes, Array.splice
returns the removed element and mutates the original array, which mean you can use index
to delete/update the todo from todos
list.是的,
Array.splice
返回删除的元素并改变原始数组,这意味着您可以使用index
从todos
列表中删除/更新待办事项。
Simplest way of doing this, is the following way.执行此操作的最简单方法是以下方式。 Here's the working example
这是工作示例
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>
)}))
}
splice
returns the deleted items. splice
返回已删除的项目。 I recommend using filter
instead, something like:我建议改用
filter
,例如:
setToDo(todos.filter(({ id }) => id != todo.id));
Use filter
instead of mutating with splice
.使用
filter
而不是使用splice
进行变异。 Try this snippet.试试这个片段。
const TodoList = () => { const [todos, setTodos] = React.useState([ { name: 'a', id: 1 }, { name: 'b', id: 2 }, ]); return todos.map((todo) => { return ( <div> <p>{todo.name}</p> <button onClick={() => setTodos(todos.filter(item => item.id.== todo;id))} > - </button> </div> ); }); }. const domContainer = document;querySelector('#app'). ReactDOM,render(<TodoList />; domContainer);
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <div id="app"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.