11import { useMemoizedFn } from 'ahooks' ;
2- import { useMemo , useState } from 'react' ;
2+ import { useMemo , useRef , useState } from 'react' ;
33import type {
44 ConfirmationDetails ,
55 ConfirmationHandler ,
@@ -25,18 +25,46 @@ export const useConfirmation = () => {
2525 details : null ,
2626 resolver : null ,
2727 } ) ;
28+ const activeRef = useRef < {
29+ details : ConfirmationDetails ;
30+ resolve : ( response : ConfirmationResponse ) => void ;
31+ } | null > ( null ) ;
32+ const queueRef = useRef <
33+ {
34+ details : ConfirmationDetails ;
35+ resolve : ( response : ConfirmationResponse ) => void ;
36+ } [ ]
37+ > ( [ ] ) ;
38+
39+ const showActive = useMemoizedFn (
40+ (
41+ entry : {
42+ details : ConfirmationDetails ;
43+ resolve : ( response : ConfirmationResponse ) => void ;
44+ } | null
45+ ) => {
46+ activeRef . current = entry ;
47+ setConfirmationState ( {
48+ isVisible : Boolean ( entry ) ,
49+ details : entry ?. details ?? null ,
50+ resolver : entry ?. resolve ?? null ,
51+ } ) ;
52+ }
53+ ) ;
2854
2955 /**
3056 * 显示确认对话框
3157 */
3258 const showConfirmation = useMemoizedFn (
3359 ( details : ConfirmationDetails ) : Promise < ConfirmationResponse > => {
3460 return new Promise ( ( resolve ) => {
35- setConfirmationState ( {
36- isVisible : true ,
37- details,
38- resolver : resolve ,
39- } ) ;
61+ const entry = { details, resolve } ;
62+ if ( ! activeRef . current ) {
63+ showActive ( entry ) ;
64+ return ;
65+ }
66+
67+ queueRef . current . push ( entry ) ;
4068 } ) ;
4169 }
4270 ) ;
@@ -45,16 +73,12 @@ export const useConfirmation = () => {
4573 * 处理用户响应
4674 */
4775 const handleResponse = useMemoizedFn ( ( response : ConfirmationResponse ) => {
48- if ( confirmationState . resolver ) {
49- confirmationState . resolver ( response ) ;
76+ if ( activeRef . current ) {
77+ activeRef . current . resolve ( response ) ;
5078 }
5179
52- // 重置状态
53- setConfirmationState ( {
54- isVisible : false ,
55- details : null ,
56- resolver : null ,
57- } ) ;
80+ const next = queueRef . current . shift ( ) ?? null ;
81+ showActive ( next ) ;
5882 } ) ;
5983
6084 /**
0 commit comments