简体   繁体   English

本地存储集项目替换而不是更新

[英]Local storage set Item replaces instead of update

I tried to save my data in local Storage with setItem but when I refresh the chrome tab and add data to my array, the data in localStorage delete the old data and set new data instead of updating that old data.我尝试使用setItem将我的数据保存在本地存储中,但是当我刷新 chrome 选项卡并将数据添加到我的数组时,localStorage 中的数据会删除旧数据并设置新数据,而不是更新旧数据。

Here is my code:这是我的代码:


let capacity = 200;
let reservedRooms = 0;
let users = [];

let rsBox = document.getElementById('reservebox');

class Reserver {
    constructor(name , lastName , nCode , rooms){
        this.name = name ;
        this.lastName = lastName ;
        this.nCode = nCode ;
        this.rooms = rooms ;
    }

    saveUser(){
        if(this.rooms > capacity){
            console.log('more than capacity');
        }else{
            users.push({
                name : this.name ,
                lastName : this.lastName ,
                id : this.nCode ,
                rooms : this.rooms
            });
            capacity -= this.rooms ;
            reservedRooms += this.rooms ;
        }
    }

    saveData(){
        localStorage.setItem('list',JSON.stringify(users));
    }



}


rsBox.addEventListener('submit',function(e){

    let rsName = document.getElementById('name').value;
    let rsLastName = document.getElementById('lastname').value;
    let rsNationalCode = Number(document.getElementById('nationalcode').value);
    let rooms = Number(document.getElementById('rooms').value);

    //Save the user data
    let sign = new Reserver(rsName , rsLastName , rsNationalCode , rooms);
    sign.saveUser();
    sign.saveData();





    e.preventDefault();
});

You are pushing an empty users array each time you reload the page, to resolve this you need to populate the users array from the items you have in storage.每次重新加载页面时,您都会推送一个空的 users 数组,要解决此问题,您需要从存储中的项目填充 users 数组。

eg例如

let users = [];

needs to be something like需要像

let users = JSON.parse(localStorage.getItem('list')) || [];

The key point being that you need to load your existing users to be able to add to them, if you don't then you are essentially creating the users array fresh each time the page loads and you put data into it.关键是您需要加载现有用户才能添加到他们中,如果您不这样做,那么您实际上是在每次加载页面并将数据放入其中时创建新的 users 数组。

You may want to create something like a "loadData" function that checks if the array is initialized, loads it if it is and creates it if it isn't.您可能想要创建类似“loadData”函数的东西,用于检查数组是否已初始化,如果已初始化则加载它,如果未初始化则创建它。 You can make this generic so that you can use it to access any key and provide a default value if the key isn't present eg您可以将其设为通用,以便您可以使用它来访问任何键并在键不存在时提供默认值,例如

function loadData(key, def) {
    var data = localStorage.getItem(key);
    return null == data ? def : JSON.parse(data)
} 

then然后

// load "list" - set to an empty array if the key isn't present
let users = loadData('list', []);

Another option would be to change the saveData method so you won't have to load the localStorage when the app is loading:另一种选择是更改saveData方法,这样您就不必在加载应用程序时加载localStorage

saveData(){
        let newList = JSON.parse(localStorage.getItem('list') || '[]')
        if(users.length) newList.push(users[users.length - 1]);
        localStorage.setItem('list',JSON.stringify(newList));
        newList=null;
}

Note: Be careful with localStorage because it doesn't have the same capacity on all browsers, you can check this post for more information注意:使用 localStorage 时要小心,因为它在所有浏览器上的容量不同,您可以查看此帖子以获取更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM