求助在本地环境 nextjs 开发, localstorage 值被清除了问题

1 月 6 日
 elza

如题

import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import type { UserInfo } from '@/service/user';
import { UserToken } from '@/interfaces/interfaces';

interface AuthState {
  accessToken: string | null;
  refreshToken: string | null;
  setTokens: (token: UserToken) => void;
  setIsHydrating: (value: boolean) => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      accessToken: null,
      refreshToken: null,
      setTokens: (token: UserToken) => set({ accessToken: token.accessToken, refreshToken: token.refreshToken }),
      setIsHydrating: (value) => set({ isHydrating: value })
    }),
    {
      name: 'auth-storage', // localStorage key
      onRehydrateStorage: () => (state) => {
        if (state) {
          console.log('rehydrated auth state:', state);
          state.setIsHydrating(false);
        }
      },
      storage: createJSONStorage(() => localStorage)
    }
  )
);

在用户登录后通过 zustand 的方式把 token 信息存储 localStorage 中,但在本地过一段时间或者代码结构调整,会发现之前 localStorage 存储的值突然没了,被清空了,变成了如下内容:

{"state":{"accessToken":null,"refreshToken":null,"isHydrating":false},"version":0}

可以肯定代码里没有任何 localStorage 的 clear 操作。

这个问题感到很疑惑,有问过 GPT ,它给我的回复是因为 nextjs 重新 rebuild 导致 localStorage 值清空,然后 export const useAuthStore = create<AuthState>() 代码被重新执行。

对这个答案保持怀疑,是这个原因导致的吗,还是其他问题?怎么解决

2833 次点击
所在节点    Next.js
2 条回复
wxxxcxx
1 月 6 日
检查下每次启动端口是不是一致的?
elza
1 月 6 日
@wxxxcxx 同一个端口

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1183566

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX