[英]react Todo list erases in console but does not erase from screen
I am trying to build a todo list and when I console log it deletes the item I am attempting to delete onclick but the item stays on the screen.我正在尝试构建一个待办事项列表,当我控制台日志时,它会删除我试图删除 onclick 的项目,但该项目仍保留在屏幕上。 what I am trying to do is delete the item from the list onclick.我想要做的是从 onclick 列表中删除该项目。
import React, { useState } from "react";
export function Todos() {
const [tasks, setTasks] = useState([]);
const deleteLabel = ind => {
tasks.splice(ind, 1);
console.log(tasks);
};
return (
<div className="container d-flex justify-content-center">
<div className="row">
<div className="col">
<input
onKeyUp={e =>
e.keyCode === 13 &&
setTasks(
tasks.concat({
label: e.target.value
})
)
}
/>
<div className="list-group">
{tasks === null
? "Loading..."
: tasks.map((t, index, myarr) => (
<a
href="#"
className="list-group-item list-group-item-action"
key={index}
onClick={() => {
deleteLabel(index);
}}>
{t.label}
</a>
))}
</div>
</div>
</div>
</div>
);
}
It's because you're not updating your state after splicing the item from your array.这是因为在拼接数组中的项目后您没有更新状态。 The component only re-renders when there is any change in the state.组件仅在状态发生任何变化时重新渲染。 You can use the update your deleteLabel
function as suggested in the previous answer:您可以按照上一个答案中的建议使用更新您的deleteLabel
函数:
const deleteLabel = ind => {
const newTasks = [...tasks]
newTasks.splice(ind, 1);
setTasks(newTasks)
console.log(newTasks);
};
i think is better to change your deleteLabel function to我认为最好将您的 deleteLabel 函数更改为
const deleteLabel = ind => {
const newTasks = [...tasks]
newTasks.splice(ind, 1);
setTasks(newTasks)
console.log(newTasks);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.