1- import { useState , useEffect } from 'react' ;
1+ import { useState , useEffect , useRef } from 'react' ;
22
33interface IProps {
44 /** 最大请求次数 */
@@ -15,50 +15,48 @@ export enum ServiceStatus {
1515 FAILURE = 'FAILURE' ,
1616}
1717
18+ let intervalId : NodeJS . Timeout ;
19+
1820/**
1921 * 轮询请求后端服务
2022 */
2123const usePollRequestService = ( { maxAttempts = 200 , interval = 200 , loopService } : IProps ) => {
2224 const [ serviceStatus , setServiceStatus ] = useState < ServiceStatus > ( ServiceStatus . PENDING ) ;
23- const [ attempts , setAttempts ] = useState ( 0 ) ;
2425 const [ restart , setRestart ] = useState ( false ) ;
26+ const attempts = useRef ( 0 ) ;
2527
26- useEffect ( ( ) => {
27- let intervalId : NodeJS . Timeout ;
28-
29- const serviceFn = async ( ) => {
30- if ( attempts >= maxAttempts ) {
31- setServiceStatus ( ServiceStatus . FAILURE ) ;
32- clearInterval ( intervalId ) ;
33- return ;
34- }
35- try {
36- setAttempts ( attempts + 1 ) ;
37- await loopService ( ) ;
38- setServiceStatus ( ServiceStatus . SUCCESS ) ;
39- clearInterval ( intervalId ) ;
40- } catch ( error ) {
41- // setAttempts(attempts + 1);
42- }
43- } ;
28+ const serviceFn = async ( ) => {
29+ // 第一次请求失败,启动服务
30+ if ( attempts . current === 1 && ServiceStatus . SUCCESS !== serviceStatus ) {
31+ window . electronApi ?. startServerForSpawn ( ) ;
32+ }
33+ if ( attempts . current >= maxAttempts ) {
34+ setServiceStatus ( ServiceStatus . FAILURE ) ;
35+ clearInterval ( intervalId ) ;
36+ return ;
37+ }
38+ try {
39+ attempts . current = attempts . current + 1 ;
40+ await loopService ( ) ;
41+ setServiceStatus ( ServiceStatus . SUCCESS ) ;
42+ clearInterval ( intervalId ) ;
43+ } catch ( error ) {
44+ // setAttempts(attempts + 1);
45+ }
46+ } ;
4447
48+ useEffect ( ( ) => {
4549 serviceFn ( ) ;
46-
4750 if ( serviceStatus !== ServiceStatus . SUCCESS ) {
48- // 第一次请求失败,启动服务
49- if ( attempts === 1 ) {
50- window . electronApi ?. startServerForSpawn ( ) ;
51- }
5251 intervalId = setInterval ( serviceFn , interval ) ;
5352 }
54-
5553 return ( ) => clearInterval ( intervalId ) ;
5654 } , [ maxAttempts , interval , restart ] ) ;
5755
5856 // 新增加的重置函数
5957 const restartPolling = ( ) => {
6058 setServiceStatus ( ServiceStatus . PENDING ) ;
61- setAttempts ( 0 ) ;
59+ attempts . current = 0 ;
6260 setRestart ( ! restart ) ;
6361 } ;
6462
0 commit comments