首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新本地存储

更新本地存储
EN

Stack Overflow用户
提问于 2020-10-23 15:16:29
回答 2查看 70关注 0票数 0

我在更新本地存储值时遇到了困难。我有“用户”数组,我想从它更新我的本地存储,但在实施过程中出现了许多问题。请看下面的代码,并注意它的学习,所以不要害怕,我使用本地存储来存储登录和密码。

代码语言:javascript
复制
class Register {
    constructor({
        inputLogin,
        inputPassword
    }) {
        this.inputLogin = inputLogin;
        this.inputPassword = inputPassword;
    }

    users = [];

    add() {

        const btn = document.querySelector('#register-form__submit');
        btn.addEventListener('click', (e) => {
            e.preventDefault();

            const usersData = {
                login: this.inputLogin.value,
                password: this.inputPassword.value
            }



            if (localStorage.getItem('users')) {

                   // // I dont know what to do here, I want to get existing value from local Storage. Put them back to array users and then set local storage with this old an new value... But I've encountered a lot of problems like nested arrays, overlooping etc. Please tell me guys how you would've done it.
            } else {
                this.users.push(usersData);
                localStorage.setItem('users', JSON.stringify(this.users));
            }

        })

    }

}

编辑:工作解决方案。我希望它能帮助那些想练习但还不了解数据库的人。

代码语言:javascript
复制
 class Register {
        constructor() {
    
            this.inputLogin = document.getElementById('login')
            this.inputPassword = document.getElementById('password')
            this.users = []
    
        }
    
    
        add() {
    //checking if inputs are empty
            if (this.inputLogin.value === '' || this.inputPassword.value === '') {
                this.alert('Musisz wypełnić wszystkie pola')
            } else {

//creating object with users data
                let userData = {
                    login: this.inputLogin.value,
                    password: this.inputPassword.value,
                }
    
    
                if (window.localStorage.getItem('users')) {

//checking if there are any users in local storage
                    const existingData = JSON.parse(window.localStorage.getItem('users'));
    
//looping through those values and checking if there is already such an user with this login.
                    for (let i = 0; i < existingData.length; i++) {
                        if (existingData[i].login === userData.login) {
                            if (document.querySelector('.red-alert')) {
                                return;
                            } else {
                                this.alert("user already exists");
                                break;
                            }
                        } else {
//checking if this.users[] is empty(this happens after refreshing page or restarting browser of course
                            if (this.users.length === 0) {
                                existingData.map((obj) => {
                                    return this.users.push(obj);
                                })
                                this.users.push(userData);
                                localStorage.setItem('users', JSON.stringify(this.users))
                                window.location.href = "index.html";
                            }
//checking if there is some data in this.users. That means page was not refreshed nor browser was restarted.

 else if (this.users.length > 0) {
                                this.users.push(userData);
                                localStorage.setItem('users', JSON.stringify(this.users))
                                console.log(this.users);
                                window.location.href = "index.html";
                            }
                        }
                    }
                }
 else {
                    //success when there are no users at all in this.users[] and local storage is empty
                    this.users.push(userData);
                    localStorage.setItem('users', JSON.stringify(this.users))
                    window.location.href = "index.html";
                }
            }

     alert(text) {
            const par = document.createElement('p')
            par.classList.add('red-alert');
            par.textContent = text;
            document.querySelector('.register-form').appendChild(par)
        }
    }
EN

回答 2

Stack Overflow用户

发布于 2020-10-23 15:23:49

您需要首先检查现有的key,然后更新本地存储的值。为了更好地理解,我添加了行内注释

代码语言:javascript
复制
// ..rest of the code 

// check if the local storage have any key by this na,e
const currStoredData = localStorage.getItem('users');
// if key esxist
if (currStoredData) {
  // push the existing value of the key in the array
  this.users.push(currStoredData);
  // set the new user data in the local storage
  localStorage.setItem(usersData)

} else {
  this.users.push(usersData);
  localStorage.setItem('users', JSON.stringify(this.users));
}

})
票数 0
EN

Stack Overflow用户

发布于 2020-10-23 15:40:42

您只能在开始时读取本地存储,并在之后使用对象。因为存储只保存字符串,所以您还需要解析值。

代码语言:javascript
复制
class Register {
    constructor({
        inputLogin,
        inputPassword
    }) {
        this.inputLogin = inputLogin;
        this.inputPassword = inputPassword;
    }

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

    add() {

        const btn = document.querySelector('#register-form__submit');
        btn.addEventListener('click', (e) => {
            e.preventDefault();

            const usersData = {
                login: this.inputLogin.value,
                password: this.inputPassword.value
            }

            this.users.push(usersData);
            localStorage.setItem('users', JSON.stringify(this.users));
        })

    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64495565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档