创建react中 函数请求叠加只会请求一次 和 对象销毁后中断接口回调的方法

// 关于接口请求方法重复运行的问题 确保每次接口返回的都是最后一次请求执行
export const SingleAction = function(Action: (...param:any)=> Promise<any>){
  // 创建唯一值
  let AccessNewTime: number = 0;;
  return function(...param: any){
    let FuncAccessNewTime = AccessNewTime = (new Date()).getTime();
    return Action(...param).then((res: any)=> {
      if( FuncAccessNewTime !== AccessNewTime ) return new Promise(()=>{});
      return res.data;
    });
  }
}


// 在react内部创建的 可以在组件被删除后才运行的Promise类型函数作阻断
export const StopPromise = function(){
  const stopPromise = useRef(false);
  useEffect(()=>{
    return function(){
      stopPromise.current = true;
    }
  }, [])
  return (res: any) => { 
    if( stopPromise.current ) 
      return new Promise(()=> {});
    return res;
  };
}

调用方法

// 产品类型统计
const single_circuitTypeStatis = SingleAction(circuitTypeStatis);
const  _circuitTypeStatis = function(province: string, stop: (param: any)=> any ,sets: any[]) {
  single_circuitTypeStatis(province)
    .then(stop)
    .then((res: any) => {
      sets.forEach((set: any)=> { set(res) });
    })
    .catch(err => {
      console.log(err);
    });
}



const stopPromise = StopPromise()

  useEffect (()=> { 
    _circuitTypeStatis(cityid || province, stopPromise, [setData])
  }, [province, cityid]);

都是伪代码  不过  不难看明白。。。

posted @ 2023-05-17 16:02  blurs  阅读(136)  评论(0编辑  收藏  举报