Explorar el Código

♻️ refactor(coupon): 重构登录认证逻辑

- 移除coupon-api中getCurrentUserId、checkAuth、redirectToLogin等工具函数
- 引入useAuth hook获取用户信息和登录状态
- 使用user.id替代getCurrentUserId()获取用户ID
- 使用isLoggedIn替代checkAuth()检查登录状态
- 将redirectToLogin替换为直接调用Taro.navigateTo跳转登录页
yourname hace 3 meses
padre
commit
982dc11135
Se han modificado 1 ficheros con 8 adiciones y 7 borrados
  1. 8 7
      mini/src/pages/index/index.tsx

+ 8 - 7
mini/src/pages/index/index.tsx

@@ -6,9 +6,10 @@ import { advertisementClient, wechatCouponStockClient } from '@/api'
 import { Button } from '@/components/ui/button'
 import { Card, CardContent, CardHeader } from '@/components/ui/card'
 import { cn } from '@/utils/cn'
-import { receiveCoupon, getCurrentUserId, checkAuth, redirectToLogin } from '@/utils/coupon-api'
+import { receiveCoupon } from '@/utils/coupon-api'
 import { Navbar } from '@/components/ui/navbar'
 import { TabBarLayout } from '@/layouts/tab-bar-layout'
+import { useAuth } from '@/utils/auth'
 
 interface Advertisement {
   id: number
@@ -35,6 +36,7 @@ interface WechatCouponStock {
 
 export default function IndexPage() {
   const queryClient = useQueryClient()
+  const { user, isLoggedIn } = useAuth()
 
   // 获取广告列表
   const { data: advertisements, isLoading: adsLoading } = useQuery({
@@ -73,11 +75,10 @@ export default function IndexPage() {
   // 领取代金券
   const receiveMutation = useMutation({
     mutationFn: async (stockId: number) => {
-      const userId = getCurrentUserId()
-      if (!userId) {
+      if (!user?.id) {
         throw new Error('请先登录')
       }
-      const result = await receiveCoupon({ stockId, userId })
+      const result = await receiveCoupon({ stockId, userId: user.id })
       if (!result.success) {
         throw new Error(result.message)
       }
@@ -97,7 +98,7 @@ export default function IndexPage() {
           content: '请先登录后再领取优惠券',
           success: (res) => {
             if (res.confirm) {
-              redirectToLogin()
+              Taro.navigateTo({ url: '/pages/login/index' })
             }
           }
         })
@@ -111,13 +112,13 @@ export default function IndexPage() {
   })
 
   const handleReceiveCoupon = (stockId: number) => {
-    if (!checkAuth()) {
+    if (!isLoggedIn) {
       Taro.showModal({
         title: '提示',
         content: '请先登录后再领取优惠券',
         success: (res) => {
           if (res.confirm) {
-            redirectToLogin()
+            Taro.navigateTo({ url: '/pages/login/index' })
           }
         }
       })