单击按钮后 localStorage 丢失数据

localStorage loses data after clicking on button

我正在尝试加载 3 个 CSV 文件并将字符串化对象保存到本地存储中。 3个CSV文件加起来不超过2MB内存。

当用户点击按钮(id="submit_files")时,程序成功将 3 个 CSV 文件保存到本地存储中。但是刷新页面时LocalStorage显示只保存了其中一两个。

当我添加“e.preventDefault();”时,我注意到所有 3 个字符串化对象都存储在 localStorage 中在按钮的事件处理程序中停止自行刷新页面。但是localStorage在刷新时显示随机保存的对象只有一两个。

代码的逻辑好像是对的,但是LocalStorage好像有不明白的地方。我怀疑刷新页面时全局变量存在问题。我错过了什么?

HTML:

<form>
    <label for="tag_csv"> Upload "tag_list.csv" file : </label>
    <input type="file" id="tag_csv" accept=".csv" required>

    <label for="radar_csv"> Upload "radar_list.csv" file : </label>
    <input type="file" id="radar_csv" accept=".csv" required>

    <label for="decisions_csv"> Upload "tag_decisions.csv" file : </label>
    <input type="file" id="decisions_csv" accept=".csv" required>

    <button type="submit" id="submit_files"> Upload File </button>
</form>

JS:

let tag_list;
let radar_list;
let decisions_list;

// Check if csv objects are saved in to local storage. 
// If true, set all three global variables to the csv objects respectively. 
$(document).ready( function(){
    if (isCsvLoaded()) {
        console.log("csv is loaded")

       // Initialize tag_list, radar_list, decisions_list
        retrieveObjects()
    } else {
        console.log("Not enough csv in localstorage")
    }
})

const submit_button = document.getElementById('submit_files');
submit_button.addEventListener('click', (e) => {
    createDict();
    // e.preventDefault();
})

function retrieveObjects() {
    tag_list = JSON.parse(localStorage.getItem('tag_list'));
    radar_list = JSON.parse(localStorage.getItem('radar_list'));
    decisions_list = JSON.parse(localStorage.getItem('decisions_list'));
}

// Use this function to parse all three CSV files and store them in local storage.
async function createDict() {
    console.log("createDict()")
    try {
        let parsed_tag_list = await parseCSV('#tag_csv')
        let tag_list_serialized = JSON.stringify(parsed_tag_list)
        localStorage.setItem("tag_list", tag_list_serialized)

        let parsed_radar_list = await parseCSV('#radar_csv')
        let radar_list_serialized = JSON.stringify(parsed_radar_list)
        localStorage.setItem("radar_list", radar_list_serialized)

        let parsed_decisions_list = await parseCSV('#decisions_csv')
        let decisions_list_serialized = JSON.stringify(parsed_decisions_list)
        localStorage.setItem("decisions_list", decisions_list_serialized)
    
    } catch (err) {
        console.log(err)
    }
};

localstorage 的最大存储容量为 ~ 5MB。要检查存储容量,试试这个:-

    const check = bytes => {
  

    try {
        localStorage.clear();
        localStorage.setItem('a', '0'.repeat(bytes));
        localStorage.clear();
        return true;
      } catch(e) {
        localStorage.clear();
        return false;
      }

};

正如@epascarello 在最初 post 的评论部分中提到的那样,我的程序有一个竞争条件,表单提交速度比我处理数据的调用速度更快。

因此,我的程序有必要在按钮处理函数中包含“e.preventDefault()”,以阻止程序在所有数据存储之前刷新页面。