为什么编辑任务函数不适用于我的函数?



我正在做一个React项目,其中我有一个任务列表;编辑";。我的思维过程是,当用户点击编辑时,它会用当前任务信息填充表单,当他们点击"编辑"时;保存编辑";它只是找到任务所在的键,删除它,然后用一个新键创建一个新任务,但所有其他信息都是相同的。然而,当我尝试此操作时,它似乎不起作用,只是删除了任务。

以下是一个片段,希望它能有所帮助:

var saveHandler = (e) => {
e.preventDefault();
props.seteId(props.editTask.id); //set the old task's key
props.setTasks([ //add our "edited" task to the list with the form info, and new key.
...props.tasks,
{
text: props.inputText,
status: props.status,
id: Math.random() * 1500, //I know this isnt a great way to do it
priority: props.priority,
},
]);
props.setTasks(props.tasks.filter((el) => el.id !== props.eId)); //find old task and delete it 

状态是异步更新的。

您调用了两次props.setTasks,但props.tasks的值在它们之间没有变化,因此您正在覆盖(而不是建立在(您所做的第一次状态更改。

请使用变量来存储中间状态。

const allTasks = [ ...props.tasks, { /* etc */ } ];
const updatedTasks = allTasks.filter( /* etc */ );
props.setTasks(updatedTasks);

同样,props.eId不会及时更新el.id !== props.eId,因此在筛选函数中使用props.editTask.id而不是props.eId

如果我能很好地理解您的需求,这应该会解决您的问题,使用旧的id props.editTask.id 进行测试

var saveHandler = (e) => {
e.preventDefault();
props.seteId(props.editTask.id); //set the old task's key
props.setTasks([ //add our "edited" task to the list with the form info, and new key.
...props.tasks,
{
text: props.inputText,
status: props.status,
id: Math.random() * 1500, //I know this isnt a great way to do it
priority: props.priority,
},
]);
props.setTasks(props.tasks.filter((el) => el.id !== props.editTask.id)); //find old task and delete it

最新更新