【发布时间】:2021-01-24 13:52:30
【问题描述】:
我知道这不是反应问题,而且我不擅长编码。谁能告诉我为什么我的代码运行得这么奇怪!
我的项目是一个简单的待办事项列表。我有 3 个组件。
- 主应用组件
- TodoList 组件
- TodoItem 组件
我想在用户单击删除图标时删除 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 对象,我也不想克隆卡片。
【问题讨论】:
-
为什么你在
TodoList的setTodoList的调用中传递index而不是cardInex? -
如何将 cardIndex 传递给 handleDeleteTodo?如果您传递了正确的索引值,请尝试使用filter 函数。
-
@k-wasilewski
todoLists是一个todoList数组,它是一个包含name和cards的对象。cards是一组卡片。为了修改 todoList 我必须通过它的索引而不是卡片的索引来访问它 -
@Miraziz
index是当前的 TodoList 数组索引。我将它作为道具从App.js传递给TodoList.js
标签: javascript reactjs react-hooks setstate react-state