如何更新 Localstorage 物件中的多個狀態 React
P粉696605833
P粉696605833 2023-09-14 11:49:00
0
1
560

所以我已經有一個保留狀態的 localStorage 掛鉤,但現在我想更新物件中的兩個項目

這是新增更新的函數

const { data, setData } = useLocalStorage();

  const addWorkExperience = () => {
    let additionJob = {
      ...data,
      jobExperience: [
        ...data.jobExperience,
        {
          city: "",
          company: "",
          country: "",
          current: false,
          endMonth: "",
          endYear: "",
          jobTitle: "",
          startMonth: "",
          startYear: "",
          state: "",
          workDesc: "",
        },
      ],
      currentEditedJob: data.currentEditedJob + 1,
    };

    setData(additionJob, console.log(additionJob, data));

當它被記錄時,它會帶來像這樣的jobExperience 數組jobExperience: (6) ['0', '1', '2', '3', '4', '5' , {…} ]只保存一個對象,其餘都轉為數字

我注意到,如果我從附加作業物件中刪除currentEditedJob: data.currentEditedJob 1, ,一切都會正常工作,並且狀態更新良好,並且它們會保存為物件jobExperience: (6 ) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]

#請問有解決辦法嗎

我嘗試一一更新狀態,但效果不佳。

setTemplateData((prev) => ({...prev,
        jobExperience: [
           ...prev.jobExperience,
           {
             city: "",
             company: "",
             country: "",
             current: false,
             endMonth: "",
             endYear: "",
             jobTitle: "",
             startMonth: "",
             startYear: "",
             state: "",
             workDesc: "",
          },
        ],
       currentEditedJob: data.currentEditedJob + 1,
     }), console.log(additionJob, data));

但除非我刪除 currentEditedJob: data.currentEditedJob 1,,否則它仍然是相同的錯誤

P粉696605833
P粉696605833

全部回覆(1)
P粉872182023

問題似乎出在 addWorkExperience 函數中的 currentEditedJob 屬性上。根據您提供的程式碼,data.currentEditedJob 似乎是數字的字串表示形式,當您向其添加 1 時,它會連接數字而不是執行算術加法。

要解決此問題,您可以將 data.currentEditedJob 轉換為數字,然後再加 1。以下是 addWorkExperience 函數的更新版本:

const currentEditedJob = parseInt(data.currentEditedJob, 10); // Convert to number
  const additionJob = {
    ...data,
    jobExperience: [
      ...data.jobExperience,
      {
        city: "",
        company: "",
        country: "",
        current: false,
        endMonth: "",
        endYear: "",
        jobTitle: "",
        startMonth: "",
        startYear: "",
        state: "",
        workDesc: "",
      },
    ],
    currentEditedJob: currentEditedJob + 1, // Perform arithmetic addition
  };

  setData(additionJob);
  console.log(additionJob, data);
};

透過使用 parseInt() 將 data.currentEditedJob 轉換為數字,加法操作將正常運作,並且狀態將如預期更新。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板