【问题标题】:NuxtJS store returning local storage values as undefinedNuxtJS 存储返回未定义的本地存储值
【发布时间】:2021-09-02 16:00:39
【问题描述】:

我有一个 nuxt 应用程序。其挂载的生命周期钩子中的一个组件是从状态存储中请求一个值,该值是从本地存储中检索的。这些值存在于本地存储中,但存储将其返回为未定义。如果我使用 {{value}} 渲染 ui 中的值 他们展示。所以看起来在代码运行的那一刻,值是未定义的。

index.js(存储):

export const state = () => ({
  token: process.browser ? localStorage.getItem("token") : undefined,
  user_id: process.browser ? localStorage.getItem("user_id") : undefined,
...

组件.vue

挂载钩子: 我正在使用 UserSerivce.getFromStorage 直接从 localStorage 获取值,否则此代码块将无法运行。说明问题是暂时的。

async mounted() {
  // check again with new code. 
  if (UserService.getFromStorage("token")) {
    console.log("user service found a token but what about store?")
    console.log(this.$store.state.token, this.$store.state.user_id);

    const values = await ["token", "user_id"].map(key => {return UserService.getFromStorage(key)});
    console.log({values});
    SocketService.trackSession(this, socket, "connect")
  }
}

安装前挂钩:

isLoggedIn 只是检查“token”属性是否设置为存储状态。 return !!this.$store.state.token

beforeMount () {
  if (this.isLoggedIn) {
    // This runs sometimes??? 80% of the time.
    console.log("IS THIS CLAUSE RUNNING?");
  }
}

视频讲解:https://www.loom.com/share/541ed2f77d3f46eeb5c2436f761442f4

【问题讨论】:

  • 问得好问题!这里发生了很多事情。这可能是生命周期问题,或者是异步的,直到解决才被阻止?很难像这样调试它。更快的方法可能是创建一个全新的项目并仔细检查所有可能的问题。然后,尝试注释掉并console.log/使用调试器。既然是 80% 的时间,可能就是这样。
  • 另外,您需要知道mountasync/await 的情况下不会阻塞。
  • 另外,您是否使用ssr?因为target: 'static' + ssr: true 比普通的ssr: false 更棘手。
  • 关于 ssr - 无论 nuxt 的默认值是什么。我没有在 nuxt.config.js 文件中明确设置该字段(尴尬哎呀。我对 vue 比较陌生)

标签: asynchronous nuxt.js vuex


【解决方案1】:

OP 的应用看起来很大,所以要找到确切的原因有点困难。
同时,设置ssr: false 修复了错误。

它提出了更多,但他们可能应该被问到另一个问题。

【讨论】:

    猜你喜欢
    • 2020-11-16
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2021-06-10
    • 2019-06-11
    • 2020-07-19
    相关资源
    最近更新 更多