修改用户登陆认证流程
This commit is contained in:
@@ -1,85 +1,14 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { View } from "@tarojs/components";
|
||||
import Taro from "@tarojs/taro";
|
||||
import { getCurrentFullPath } from '@/utils';
|
||||
import { check_login_status, clear_login_state } from "@/services/loginService";
|
||||
import React from "react";
|
||||
import { check_login_status } from "@/services/loginService";
|
||||
|
||||
// withAuth 现在改为可选登录检查,不强制跳转
|
||||
// 如果需要强制登录,请在组件内部使用 requireLogin() 工具函数
|
||||
export default function withAuth<P extends object>(
|
||||
WrappedComponent: React.ComponentType<P>,
|
||||
) {
|
||||
const ComponentWithAuth: React.FC<P> = (props: P) => {
|
||||
const [authed, setAuthed] = useState<boolean | null>(null); // null表示未检查
|
||||
const [isChecking, setIsChecking] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
setIsChecking(true);
|
||||
try {
|
||||
const is_login = check_login_status();
|
||||
|
||||
if (!is_login) {
|
||||
// 未登录,清除可能过期的状态
|
||||
clear_login_state();
|
||||
const currentPage = getCurrentFullPath();
|
||||
// 跳转到登录页,并保存当前页面路径用于登录后跳转
|
||||
(Taro as any).redirectTo({
|
||||
url: `/login_pages/index/index${
|
||||
currentPage ? `?redirect=${encodeURIComponent(currentPage)}` : ""
|
||||
}`,
|
||||
});
|
||||
setAuthed(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setAuthed(true);
|
||||
} catch (error) {
|
||||
console.error('检查登录状态失败:', error);
|
||||
clear_login_state();
|
||||
(Taro as any).redirectTo({ url: '/login_pages/index/index' });
|
||||
setAuthed(false);
|
||||
} finally {
|
||||
setIsChecking(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
// 正在检查登录状态,显示空白页面避免闪烁
|
||||
if (isChecking || authed === null) {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
width: "100vw",
|
||||
height: "100vh",
|
||||
backgroundColor: "#FAFAFA",
|
||||
position: "fixed",
|
||||
top: 0,
|
||||
left: 0,
|
||||
zIndex: 999,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// 未登录,显示空白页面(已跳转,这里只是防止渲染)
|
||||
if (!authed) {
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
width: "100vw",
|
||||
height: "100vh",
|
||||
backgroundColor: "#FAFAFA",
|
||||
position: "fixed",
|
||||
top: 0,
|
||||
left: 0,
|
||||
zIndex: 999,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// 已登录,正常渲染组件
|
||||
// 不再强制检查登录状态,直接渲染组件
|
||||
// 组件内部可以在需要时调用 requireLogin() 进行检查
|
||||
return <WrappedComponent {...props} />;
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user