所以我已經有一個保留狀態的 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,
,否則它仍然是相同的錯誤
問題似乎出在 addWorkExperience 函數中的 currentEditedJob 屬性上。根據您提供的程式碼,data.currentEditedJob 似乎是數字的字串表示形式,當您向其添加 1 時,它會連接數字而不是執行算術加法。
要解決此問題,您可以將 data.currentEditedJob 轉換為數字,然後再加 1。以下是 addWorkExperience 函數的更新版本:
透過使用 parseInt() 將 data.currentEditedJob 轉換為數字,加法操作將正常運作,並且狀態將如預期更新。