[英]Deleting an array element of a react state
我知道这不是反应问题,而且我很擅长编码。 有人可以告诉我为什么我的代码运行如此奇怪!
我的项目是一个简单的待办事项列表。 我有 3 个组件。
当用户单击删除图标时,我想删除 TodoItem。
这是 app.js :
const [todoLists, setTodoLists] = useState([]);
function setTodoList(index, setFunction) {
setTodoLists(prevTodoLists => {
const newTodoLists = [...prevTodoLists]
newTodoLists[index] = {...setFunction(newTodoLists[index])};
console.log([...newTodoLists])
return [...newTodoLists];
});
}
return (
<section className="todoContainer" id="todocontainer">
{
todoLists.map((todoList, index) => {
return <TodoList todoList={todoList} index={index} setTodoList={setTodoList} />;
})
}
</section>
);
这是 TodoList.js
function handleDeleteTodo(cardIndex) {
setTodoList(index, prevTodoList => {
const newTodoList = {...prevTodoList};
newTodoList.cards.splice(cardIndex, 1);
return {...newTodoList};
});
}
return (
<section className="body" ref={todosBodyRef} >
{
todoList.cards.map((todo, cardIndex) => {
return <TodoItem listIndex={index} cardIndex={cardIndex} todo={todo} handleDeleteTodo={handleDeleteTodo} />
})
}
</section>
);
这是 TodoItem.js
function deleteButtonOnClick() {
handleDeleteTodo(cardIndex);
}
return (
<>
<p>{todo.name}</p>
<div className="controls">
<i className="far fa-trash-alt deleteCard" onClick={deleteButtonOnClick}></i>
</div>
</>
)
当我单击“删除图标”时,如果 TodoItem 是最后一个 TodoItem,它会完美删除,但如果它不是最后一个项目,它将删除接下来的 2 个 Todoitems 而不是它本身。
我不知道我做错了什么。 如果有人向我解释发生了什么,那就太好了:_(
编辑:我在handleDeleteTodo
添加了这个 if 语句:
if (newTodoList.cards == prevTodoList.cards) {
console.log("True"); // It means both cards references are Same.
}
它记录为真。 这意味着两张卡的引用是相同的,我也必须克隆它。
有没有办法在不cards
阵列的情况下解决这个问题? 因为我正在克隆整个todoList
Object 而我也不想克隆卡片。
我发现了问题!
我使用的是嵌套的 JS object,我正在使用扩展运算符克隆它。 (这是一个浅拷贝,它不会克隆对象内部的对象!)
所以我使用了 rfdc并使用它深度克隆了我的 object。 在TodoList.js中像这样:
import clone from 'rfdc/default';
function handleDeleteTodo(cardIndex) {
setTodoList(index, prevTodoList => {
const newTodoList = clone(prevTodoList); // This is where cloning happens
newTodoList.cards.splice(cardIndex, 1);
return newTodoList;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.