如何更新 Localstorage 对象中的多个状态 React
P粉696605833
P粉696605833 2023-09-14 11:49:00
0
1
566

所以我已经有一个保留状态的 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 转换为数字,加法操作将正常工作,并且状态将按预期更新。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板