【问题标题】:Cannot read property 'id' of null in vuex store module from Localstorage无法从 Localstorage 读取 vuex 存储模块中 null 的属性“id”
【发布时间】:2019-08-03 23:42:15
【问题描述】:

我有一个当前用户的存储模块。基本上,在我登录到我的应用程序后,我会在其中保留用户数据。但是,当我注销时,我会被重定向到登录页面,并在注销时从本地存储中删除当前用户数据。

但是一旦我退出,我的控制台就会出现这个错误:

无法读取 null 的属性“id”

这是因为我在当前用户模块中初始化值的方式如下:

const currentUser = {
    state: {
        id: JSON.parse(localStorage.getItem('current-user')).id || '',
        username: JSON.parse(localStorage.getItem('current-user')).username || '',
    },

所以它尝试访问本地存储对象,因为我在注销时将其删除,所以该对象不再存在。 处理此问题的最佳方法是什么?我是 vue 的新手,所以即使一开始我也不确定我正在做的事情是否是一件好事。

【问题讨论】:

    标签: javascript vue.js local-storage vuex vuex-modules


    【解决方案1】:

    如果涉及任何类型的逻辑(即使它只是检查是否存在),我认为 getter 将是一个更好的解决方案。

    尝试:

    const curentUser = {
      getters: {
        id() {
          const cu = localStorage.getItem('current-user');
          if (cu) {
            return JSON.parse(cu).id;
          }
          return '';
        },
        username() {
          const cu = localStorage.getItem('current-user');
          if (cu) {
            return JSON.parse(cu).username;
          }
          return '';
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      试试这个

      const currentUser = {
              state: {
                  id:JSON.parse(localStorage.getItem('current-user')) && JSON.parse(localStorage.getItem('current-user')).id || '',
                  username: JSON.parse(localStorage.getItem('current-user')).username || '',
              }
      

      【讨论】:

      • 好的,非常感谢!这行得通!另外,您认为我如何使用 vuex 对象并对其进行初始化是一种好习惯吗?
      • 是的,这并没有什么坏处。如果您觉得正确,请点赞并接受我的回答。让其他用户也能从中受益
      猜你喜欢
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多