簡體   English   中英

為什么編輯任務 function 不適用於我的 function?

[英]Why isn't the edit task function working for my function?

我正在開發一個 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 

State 異步更新。

您調用props.setTasks兩次,但props.tasks的值在它們之間沒有變化,因此您正在覆蓋(而不是構建)您所做的第一個 state 更改。

改為使用變量來存儲中間 state。

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

同樣, props.eId不會及時更新el.id.== props.eId ,因此請在過濾器 function 中使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM