Browse Source

🐛 fix(auth): 修复小程序启动时的静默登录逻辑

- 将静默登录触发时机从查询用户信息时调整到小程序启动时
- 移除查询用户信息时的冗余静默登录调用
- 当token无效时仅清除存储而不再触发静默登录,避免循环调用
yourname 3 tháng trước cách đây
mục cha
commit
4b8049624d
1 tập tin đã thay đổi với 9 bổ sung5 xóa
  1. 9 5
      mini/src/utils/auth.tsx

+ 9 - 5
mini/src/utils/auth.tsx

@@ -1,5 +1,5 @@
 import { createContext, useContext, PropsWithChildren } from 'react'
 import { createContext, useContext, PropsWithChildren } from 'react'
-import Taro from '@tarojs/taro'
+import Taro, { useLaunch } from '@tarojs/taro'
 import { authClient } from '../api'
 import { authClient } from '../api'
 import { InferResponseType, InferRequestType } from 'hono'
 import { InferResponseType, InferRequestType } from 'hono'
 import { QueryClient, useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
 import { QueryClient, useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
@@ -65,13 +65,18 @@ export const AuthProvider: React.FC<PropsWithChildren> = ({ children }) => {
     }
     }
   })
   })
 
 
+  
+
+  // 在小程序启动时执行静默登录,刷新token和sessionKey
+  useLaunch(() => {
+    silentLoginMutation.mutate()
+  })
+
   const { data: user, isLoading } = useQuery<User | null, Error>({
   const { data: user, isLoading } = useQuery<User | null, Error>({
     queryKey: ['currentUser'],
     queryKey: ['currentUser'],
     queryFn: async () => {
     queryFn: async () => {
       const token = Taro.getStorageSync('mini_token')
       const token = Taro.getStorageSync('mini_token')
       if (!token) {
       if (!token) {
-        // 如果没有token,尝试静默登录
-        silentLoginMutation.mutate()
         return null
         return null
       }
       }
       try {
       try {
@@ -83,8 +88,7 @@ export const AuthProvider: React.FC<PropsWithChildren> = ({ children }) => {
         Taro.setStorageSync('userInfo', JSON.stringify(user))
         Taro.setStorageSync('userInfo', JSON.stringify(user))
         return user
         return user
       } catch (error) {
       } catch (error) {
-        // token无效,尝试静默登录
-        silentLoginMutation.mutate()
+        // token无效,清除存储
         Taro.removeStorageSync('mini_token')
         Taro.removeStorageSync('mini_token')
         Taro.removeStorageSync('userInfo')
         Taro.removeStorageSync('userInfo')
         return null
         return null