简体   繁体   English

我如何解决本地存储和JavaScript问题

[英]how do i solve issue with local storage and javascript

I created a sign up with relevant functions to save a user data as they sign up. 我创建了具有相关功能的注册,以在用户注册时保存用户数据。 I don't seem to get what the issue is but the data isn't saving to the local storage. 我似乎没有得到什么问题,但是数据没有保存到本地存储中。 I should be working well but I can't figure out what the problem is. 我应该工作良好,但我不知道问题出在哪里。

the javascript file does the following 1) handles cases where someone is duplicating data with the email 2) saving an object to the local storage which is passed into an array javascript文件执行以下操作1)处理有人通过电子邮件复制数据的情况2)将对象保存到传递到数组的本地存储中

 var signUpBtn = document.querySelector('#signUp'); var signUpOver = document.querySelector('.signup__overlay'); var signInBtn = document.querySelector('#signIn'); var signInOver = document.querySelector('.signin__overlay'); var fullname = document.querySelector('#name'); var email = document.querySelector('#email'); var password = document.querySelector('#password'); var age = document.querySelector('#age'); var occupation = document.querySelector('#occupation'); var Address = document.querySelector('#address'); var signupSubmitClicked = document.querySelector('#signupClicked'); signupSubmitClicked.addEventListener('click', () => { if (fullname.value=="" || email.value=="" || password.value=="" || age.value=="" || occupation.value=="" || Address.value=="") { alert("incomplete datails, please fill up everything") } else { alert("item created") addUser(fullname, email, password, age, occupation, Address); } }); var fetchUsers = () => { try { var userString = localStorage.getItem('userData'); return JSON.parse(userString); } catch (error) { return []; } }; var saveUser = (users) => { localStorage.setItem('userData', JSON.stringify(users)); }; var addUser = (fullname, email, password, age, occupation, Address) => { var users = fetchUsers(); var user = { fullname, email, password, age, occupation, Address }; var duplicateUsers = users.filter(user => user.email === email); if (duplicateUsers.length === 0) { users.push(user); saveUser(users); return user; } }; /************* signup popup *************/ signUpBtn.addEventListener('click', () => { signUpOver.style.display = 'block'; }); signUpOver.addEventListener('click', () => { if(event.target == signUpOver){ signUpOver.style.display = "none"; } }); /************* signup popup *************/ /************* signin popup *************/ signInBtn.addEventListener('click', () => { signInOver.style.display = 'block'; }); signInOver.addEventListener('click', () => { if(event.target == signInOver){ signInOver.style.display = "none"; } }); /************* signin popup *************/ /** the end */ 
 body { width: 100%; margin: 0; background-color: #F8F9F9; display: flex; flex-direction: column; justify-content: space-around; align-items: center; align-content: center; } #mainPage, #userPage { width: 100%; display: flex; flex-direction: column; justify-content: space-around; align-items: center; align-content: center; } #userPage { display: none; } /******************** overlay ********************/ .signup__overlay { position: fixed; display: none; top: 0px; left: 0px; right: 0px; bottom: 0px; background-color: rgba(0,0,0,0.8); z-index: 1; } .signup__content{ position: relative; width: 100%; max-width: 520px; background-color: #ffffff; opacity: 1; margin: 64px auto; padding: 20px; } .signin__overlay { position: fixed; display: none; top: 0px; left: 0px; right: 0px; bottom: 0px; background-color: rgba(0,0,0,0.8); z-index: 1; } .signin__content{ position: relative; width: 100%; max-width: 520px; background-color: #ffffff; opacity: 1; margin: 64px auto; padding: 20px; } /******************** overlay ending ********************/ .headerMain { background-color: #000; color: #fff; width: 100%; margin-bottom: 50px; height: 50px; display: flex; flex-direction: row; align-items: center; align-content: center; justify-content: flex-start; } .headerUser { background-color: #000; color: #fff; width: 100%; margin-bottom: 50px; height: 50px; display: flex; flex-direction: row; align-items: center; align-content: center; justify-content: flex-start; } .upButton { margin-bottom: 20px; } .upButton, .inButton { padding-top: 15px; padding-bottom: 15px; cursor: pointer; width: 100%; max-width: 200px; background-color: #239B56; border: #239B56; color: snow; } label { padding-top: 20px; } label, input { width: 100%; } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>User system</title> <link rel="stylesheet" href="css/index.css"> </head> <body> <div id="mainPage"> <div class="signup__overlay"> <div class="signup__content"> <form> <label for="name">Full Name</label> <input required type="text" id="name" name="name"> <label for="email">Email</label> <input required type="text" id="email" name="email"> <label for="password">Password</label> <input required type="password" id="password" name="password"> <label for="age">Age</label> <input required type="text" id="age" name="age"> <label for="occupation">Occupation</label> <input required type="text" id="occupation" name="occupation"> <label for="address">Address</label> <input required type="text" id="address" name="address"> <input type="submit" id="signupClicked"> </form> </div> </div> <div class="signin__overlay"> <div class="signin__content"> <form> <label for="email">Email</label> <input required type="text" id="Email" name="email"> <label for="email">Password</label> <input required type="Password" id="Password" name="Password"> <input type="submit" id="signinClicked"> </form> </div> </div> <header class="headerMain">User System</header> <section> <button class="upButton" id="signUp">Sign Up</button> <button class="inButton" id="signIn">Sign In</button> </section> </div> <div id="userPage"> <header class="headerUser">User System</header> <section> </section> </div> <script src="js/index.js"></script> </body> </html> 

You're not handling the case when your LocalStorage entry is empty at the beginning where it returns null . LocalStorage条目在返回null的开头为空时,您将无法处理这种情况。 JSON.parse(null); is just null , so fetchUsers returns null , but then you proceed with 只是null ,所以fetchUsers返回null ,但是接着继续

var users = fetchUsers();
// …
var duplicateUsers = users.filter(user => user.email === email);

which should result in TypeError: users is null , if you open the browser console (dev tools) (hit F12 ) and read this error. 如果您打开浏览器控制台(开发工具) (按F12 )并读取此错误,则应导致TypeError: users is null

Instead, default to [] like this: 相反,默认为[]如下所示:

var fetchUsers = () => {
  try {
      var userString = localStorage.getItem('userData');
      return JSON.parse(userString) || [];
  } catch (error) {
      return [];
  }
};

Other things: 其他事情:

  • As pointed out by epascarello , you should prevent the submit when the form isn't completely filled. epascarello指出的 ,当表单未完全填写时,您应阻止提交。 You may want to prevent the default unconditionally and submit the form programatically, depending on your needs: 您可能需要无条件阻止默认设置并以编程方式提交表单,具体取决于您的需求:
signupSubmitClicked.addEventListener('click', (e) => {
  if (fullname.value=="" || email.value=="" || password.value=="" || age.value=="" || occupation.value=="" || Address.value=="") {
    alert("incomplete datails, please fill up everything");
    e.preventDefault();
  } else {
    alert("item created");
    addUser(fullname, email, password, age, occupation, Address);
  }
});

See MDN documentation Window.localStorage . 请参阅MDN文档Window.localStorage Note you must strinigify any objects prior to storing them to localstorage with JSON.stringify then you can parse them back to an object when you read them back. 请注意,在使用JSON.stringify将它们存储到本地存储之前,必须对所有对象进行分类,然后在读回它们时可以将它们解析回一个对象。

localStorage.setItem('myCat', 'Tom'); localStorage.setItem('myCat','Tom');

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

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