【发布时间】:2021-12-16 23:36:43
【问题描述】:
我正在使用 React Hooks 创建任务列表(简单的待办事项应用程序),但在删除一项时遇到了一些问题。 我正在从该状态的数组中呈现该任务列表。 我正在获取该项目的 id,在数组中找到索引,拼接然后再次将新拼接的数组设置为状态,虽然我可以在控制台上看到更改,但我的 ui 永远不会更新。我尝试使用 useEffect 挂钩,但也没有成功。 有人可以解释我做错了什么吗? 这是我在父组件上的代码
const [ todoList, setTodoList ] = useState(data);
const handleToggleComplete = (id) => {
let mapped = todoList.map(task => {
return task.id === Number(id) ? { ...task, complete: !task.complete } : { ...task};
});
setTodoList(mapped);
}
const deleteItem = (id) => {
// gets id of the button triggered
const index = todoList.map(todo => todo.id).indexOf(Number(id))
// finds index of that id
const updatedList = [...todoList];
// splices array .splice(index, 1)
updatedList.splice(index, 1)
// sets new array as state
setTodoList(updatedList)
}
return (
<div className="App">
<Header />
<TodoList todoList={todoList} handleToggleComplete={handleToggleComplete} deleteItem={deleteItem}/>
</div>
);
}
这是我的子组件
const handleClick = (event) => {
event.preventDefault()
handleToggleComplete(event.currentTarget.id)
}
const handleDelete = (event) => {
event.preventDefault()
deleteItem(event.currentTarget.parentNode.id)
}
return (
<div id={todo.id} onClick={handleClick} className={todo.complete ? "todo strike" : "todo"}>
{todo.task}
<button onClick={handleDelete}>Delete</button>
</div>
);
};
【问题讨论】:
-
嗨,看看这个答案,这是你的问题的解决方案stackoverflow.com/a/58556049/17684992
-
我认为你需要展示更多的子组件。我没有看到提供的代码有任何问题。但是作为一项改进,您已经有了
todo.id,因此您不需要做currentTarget的东西,直接使用ID 即可。 -
同意,没有足够的上下文来了解为什么删除待办事项不会在 UI 中更新。此外,使用 todo id 不需要迭代 todos 数组 3 次来删除一个元素,这就是
Array.prototype.filter的用途???? .您能否更新您的问题以包含更全面的minimal, complete, and reproducible code example? -
您好!我发现了我的问题:在我的子组件上,我触发了两个最终导致状态更改的事件,因此我的两个事件相互竞争。解决方案是使用
event.stopPropagation()
标签: reactjs react-hooks