NuxtJS 存储将本地存储值返回为未定义
NuxtJS store returning local storage values as undefined
我有一个 nuxt 应用程序。它的挂载生命周期挂钩中的一个组件正在从状态存储中请求一个值,该值是从本地存储中检索的。这些值存在于本地存储中,但存储 returns 未定义。如果我用 {{value}} 渲染 ui 中的值
他们展示。所以看起来在代码 运行s 的那一刻,值是未定义的。
index.js(商店):
export const state = () => ({
token: process.browser ? localStorage.getItem("token") : undefined,
user_id: process.browser ? localStorage.getItem("user_id") : undefined,
...
Component.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 只是检查“令牌”属性 是否设置为存储状态。
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
OP 的应用程序看起来很大,所以找到确切原因有点困难。
同时,设置 ssr: false
修复了错误。
它提出了更多,但他们可能仍然应该被问到另一个问题。
我有一个 nuxt 应用程序。它的挂载生命周期挂钩中的一个组件正在从状态存储中请求一个值,该值是从本地存储中检索的。这些值存在于本地存储中,但存储 returns 未定义。如果我用 {{value}} 渲染 ui 中的值 他们展示。所以看起来在代码 运行s 的那一刻,值是未定义的。
index.js(商店):
export const state = () => ({
token: process.browser ? localStorage.getItem("token") : undefined,
user_id: process.browser ? localStorage.getItem("user_id") : undefined,
...
Component.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 只是检查“令牌”属性 是否设置为存储状态。
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
OP 的应用程序看起来很大,所以找到确切原因有点困难。
同时,设置 ssr: false
修复了错误。
它提出了更多,但他们可能仍然应该被问到另一个问题。