2025-03-04 03:38:50 +08:00
|
|
|
|
import { useDispatch, useSelector } from 'react-redux';
|
|
|
|
|
import AppRouter from './router/router';
|
|
|
|
|
import { checkAuthThunk } from './store/auth/auth.thunk';
|
|
|
|
|
import { useEffect } from 'react';
|
|
|
|
|
import { useNavigate } from 'react-router-dom';
|
|
|
|
|
import { login } from './store/auth/auth.slice';
|
2025-03-25 08:04:35 +08:00
|
|
|
|
import { initWebSocket, closeWebSocket } from './services/websocket';
|
|
|
|
|
import { setWebSocketConnected } from './store/notificationCenter/notificationCenter.slice';
|
2025-02-27 06:54:19 +08:00
|
|
|
|
|
|
|
|
|
function App() {
|
2025-03-04 03:38:50 +08:00
|
|
|
|
const navigate = useNavigate();
|
|
|
|
|
const dispatch = useDispatch();
|
|
|
|
|
|
|
|
|
|
const { user } = useSelector((state) => state.auth);
|
2025-03-25 08:04:35 +08:00
|
|
|
|
const { isConnected } = useSelector((state) => state.notificationCenter);
|
2025-03-04 03:38:50 +08:00
|
|
|
|
|
2025-03-25 08:04:35 +08:00
|
|
|
|
// 检查用户认证状态
|
2025-03-04 03:38:50 +08:00
|
|
|
|
useEffect(() => {
|
2025-03-04 07:22:05 +08:00
|
|
|
|
handleCheckAuth();
|
2025-03-04 03:38:50 +08:00
|
|
|
|
}, [dispatch]);
|
|
|
|
|
|
2025-03-25 08:04:35 +08:00
|
|
|
|
// 管理WebSocket连接
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
console.log(user, isConnected);
|
|
|
|
|
|
|
|
|
|
// 如果用户已认证但WebSocket未连接,则初始化连接
|
|
|
|
|
if (user && !isConnected) {
|
2025-03-25 09:47:30 +08:00
|
|
|
|
// initWebSocket()
|
|
|
|
|
// .then(() => {
|
2025-03-25 08:04:35 +08:00
|
|
|
|
// dispatch(setWebSocketConnected(true));
|
|
|
|
|
// console.log('WebSocket connection initialized');
|
2025-03-25 09:47:30 +08:00
|
|
|
|
// })
|
|
|
|
|
// .catch((error) => {
|
|
|
|
|
// console.error('Failed to initialize WebSocket connection:', error);
|
|
|
|
|
// });
|
2025-03-25 08:04:35 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 组件卸载或用户登出时关闭WebSocket连接
|
|
|
|
|
return () => {
|
|
|
|
|
if (isConnected) {
|
|
|
|
|
closeWebSocket();
|
|
|
|
|
dispatch(setWebSocketConnected(false));
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}, [user, isConnected, dispatch]);
|
|
|
|
|
|
2025-03-04 03:38:50 +08:00
|
|
|
|
const handleCheckAuth = async () => {
|
|
|
|
|
console.log('app handleCheckAuth');
|
2025-03-04 07:22:05 +08:00
|
|
|
|
try {
|
|
|
|
|
await dispatch(checkAuthThunk()).unwrap();
|
2025-03-20 01:06:52 +08:00
|
|
|
|
if (!user) navigate('/login');
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.log('error', error);
|
|
|
|
|
navigate('/login');
|
|
|
|
|
}
|
2025-03-04 03:38:50 +08:00
|
|
|
|
};
|
|
|
|
|
|
2025-02-27 06:54:19 +08:00
|
|
|
|
return <AppRouter></AppRouter>;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default App;
|