NuxtJS存储返回的本地存储值为undefined



我有下一个应用程序。它挂载的生命周期钩子中的一个组件正在从状态存储中请求一个值,这个值是从本地存储中检索的。这些值存在于本地存储中,但存储将其返回为未定义。如果我用{{value}}呈现ui中的值他们表演。因此,在代码运行的那一刻,该值似乎是未定义的。

index.js(店):

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

Component.vue

安装钩:我用的是userservice。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")
}
}

BeforeMount钩:

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

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

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

最新更新