feat: 优化依赖
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
// src/hooks/useSubscription.js
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { logger } from '../utils/logger';
|
||||
|
||||
@@ -104,10 +104,32 @@ export const useSubscription = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// ⚡ 提取 userId 为独立变量,避免 user 对象引用变化导致无限循环
|
||||
const userId = user?.id;
|
||||
const prevUserIdRef = useRef(userId);
|
||||
const prevIsAuthenticatedRef = useRef(isAuthenticated);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSubscriptionInfo();
|
||||
// ⚡ 只在 userId 或 isAuthenticated 真正变化时才请求
|
||||
const userIdChanged = prevUserIdRef.current !== userId;
|
||||
const authChanged = prevIsAuthenticatedRef.current !== isAuthenticated;
|
||||
|
||||
if (userIdChanged || authChanged) {
|
||||
logger.debug('useSubscription', 'fetchSubscriptionInfo 触发', {
|
||||
userIdChanged,
|
||||
authChanged,
|
||||
prevUserId: prevUserIdRef.current,
|
||||
currentUserId: userId,
|
||||
prevAuth: prevIsAuthenticatedRef.current,
|
||||
currentAuth: isAuthenticated
|
||||
});
|
||||
|
||||
prevUserIdRef.current = userId;
|
||||
prevIsAuthenticatedRef.current = isAuthenticated;
|
||||
fetchSubscriptionInfo();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isAuthenticated, user?.id]); // 只依赖 user.id,避免 user 对象变化导致无限循环
|
||||
}, [isAuthenticated, userId]); // 使用 userId 原始值,而不是 user?.id 表达式
|
||||
|
||||
// 获取订阅级别数值
|
||||
const getSubscriptionLevel = (type = null) => {
|
||||
|
||||
Reference in New Issue
Block a user