reconnect-modal.tsx
TypeScript
import { Modal } from 'antd';
import React, { useEffect, useState } from 'react';
interface ReconnectModalProps {
open: boolean;
onReconnect: () => void;
onCancel: () => void;
}
const ReconnectModal: React.FC<ReconnectModalProps> = ({ open, onReconnect, onCancel }) => {
const [visible, setVisible] = useState(false);
useEffect(() => {
setVisible(open);
}, [open]);
const handleOk = () => {
onReconnect();
setVisible(false);
};
const handleCancel = () => {
onCancel();
setVisible(false);
};
// 处理回车键
useEffect(() => {
const handleKeyPress = (e: KeyboardEvent) => {
if (visible && e.key === 'Enter') {
handleOk();
}
};
window.addEventListener('keydown', handleKeyPress);
return () => window.removeEventListener('keydown', handleKeyPress);
}, [visible]);
return (
<Modal
title="当前连接已断开,是否重新连接"
open={visible}
onOk={handleOk}
onCancel={handleCancel}
okText="重新连接"
cancelText="取消"
/>
);
};
export default ReconnectModal;
index.tsx
TypeScript
import ReconnectModal from './reconnect-modal';
const [showReconnectModal, setShowReconnectModal] = useState(false);
const reconnectDebounceRef = useRef<NodeJS.Timeout | null>(null);
// 防抖处理,确保只触发一次弹窗
useEffect(() => {
const subscription = socketService.sendEvent$.subscribe(event => {
if (actionService?.reconnect && event === SendEventEnum.Reconnect) {
// 防抖处理,确保只触发一次弹窗
if (reconnectDebounceRef.current) {
clearTimeout(reconnectDebounceRef.current);
}
reconnectDebounceRef.current = setTimeout(() => {
setShowReconnectModal(true);
}, 300);
}
});
return () => {
subscription.unsubscribe();
if (reconnectDebounceRef.current) {
clearTimeout(reconnectDebounceRef.current);
}
};
}, [actionService, socketService.sendEvent$]);
<ReconnectModal
open={showReconnectModal}
onReconnect={() => {
actionService?.reconnect?.();
setShowReconnectModal(false);
}}
onCancel={() => {
setShowReconnectModal(false);
}}
/>