V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
elza
V2EX  ›  Next.js

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

  •  
  •   elza · 3 天前 · 366 次点击

    如题

    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>() 代码被重新执行。

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

    2 条回复    2026-01-06 18:36:43 +08:00
    wxxxcxx
        1
    wxxxcxx  
       3 天前
    检查下每次启动端口是不是一致的?
    elza
        2
    elza  
    OP
       3 天前
    @wxxxcxx 同一个端口
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   2792 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 07:33 · PVG 15:33 · LAX 23:33 · JFK 02:33
    ♥ Do have faith in what you're doing.