feat: user 依赖优化

This commit is contained in:
zdl
2025-10-24 12:19:37 +08:00
parent 5eb4227e29
commit e91656d332
3 changed files with 97 additions and 57 deletions

View File

@@ -26,6 +26,9 @@ export const AuthProvider = ({ children }) => {
const toast = useToast();
const { showWelcomeGuide } = useNotification();
// ⚡ 使用 ref 保存最新的 isAuthenticated 值,避免事件监听器重复注册
const isAuthenticatedRef = React.useRef(isAuthenticated);
// 检查Session状态
const checkSession = async () => {
try {
@@ -57,19 +60,27 @@ export const AuthProvider = ({ children }) => {
});
if (data.isAuthenticated && data.user) {
setUser(data.user);
setIsAuthenticated(true);
// ⚡ 只在 user 数据真正变化时才更新状态,避免无限循环
setUser((prevUser) => {
// 比较用户 ID如果相同则不更新
if (prevUser && prevUser.id === data.user.id) {
return prevUser;
}
return data.user;
});
setIsAuthenticated((prev) => prev === true ? prev : true);
} else {
setUser(null);
setIsAuthenticated(false);
setUser((prev) => prev === null ? prev : null);
setIsAuthenticated((prev) => prev === false ? prev : false);
}
} catch (error) {
logger.error('AuthContext', 'checkSession', error);
// 网络错误或超时,设置为未登录状态
setUser(null);
setIsAuthenticated(false);
setUser((prev) => prev === null ? prev : null);
setIsAuthenticated((prev) => prev === false ? prev : false);
} finally {
setIsLoading(false);
// ⚡ 只在 isLoading 为 true 时才设置为 false避免不必要的状态更新
setIsLoading((prev) => prev === false ? prev : false);
}
};
@@ -79,11 +90,17 @@ export const AuthProvider = ({ children }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// ⚡ 同步 isAuthenticated 到 ref
useEffect(() => {
isAuthenticatedRef.current = isAuthenticated;
}, [isAuthenticated]);
// 监听路由变化检查session处理微信登录回调
// ⚡ 移除 isAuthenticated 依赖,使用 ref 避免重复注册事件监听器
useEffect(() => {
const handleRouteChange = () => {
// 如果是从微信回调返回的重新检查session
if (window.location.pathname === '/home' && !isAuthenticated) {
// 使用 ref 获取最新的认证状态
if (window.location.pathname === '/home' && !isAuthenticatedRef.current) {
checkSession();
}
};
@@ -91,7 +108,7 @@ export const AuthProvider = ({ children }) => {
window.addEventListener('popstate', handleRouteChange);
return () => window.removeEventListener('popstate', handleRouteChange);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isAuthenticated]);
}, []); // ✅ 空依赖数组,只注册一次事件监听器
// 更新本地用户的便捷方法
const updateUser = (partial) => {