【问题标题】:How can i show page loader when 2 or more api call is there?当存在 2 个或更多 api 调用时,如何显示页面加载器?
【发布时间】:2022-12-03 17:15:05
【问题描述】:

基本上我创建了 1 个状态[isLoading, setIsLoading]=useState(false)

我有 3 个需要调用的 api。

const api1 = ()=>{
 setIsLoading(true)
 callApi()
 setIsLoading(false)
}

const api2 = ()=>{
 setIsLoading(true)
 callApi()
 setIsLoading(false)
}

const api3 = ()=>{
 setIsLoading(true)
 callApi()
 setIsLoading(false)
}

我在 useEffect() 中调用这 3 个函数。 使用 axios 调用 api, 每当任何一个 api 调用成功时,它都会将 setIsLoading() 设置为 false。所以加载动画停止了。 还有其他2个api没有完成。

基本上我需要在完成所有 api 调用后停止加载程序。

在用户界面部分,我只是在做isLoading && <Loader />

  • 一个解决方案是创建 3 个状态并使用类似(isLoading1 || isLoading2 || isLoading3) && <Loader />

但我不喜欢像这样创建多个状态。

有更好的方法来处理这个加载动画吗?

【问题讨论】:

    标签: reactjs rxjs


    【解决方案1】:

    你可以有一个像这样的状态变量:

    loadingCounter
    

    然后在callApi之前的每个函数中增加它,当callApi完成时,减少它。

    因此,如果 loadingCounter > 0 则意味着数据仍在从某个地方加载。

    或查看Promise.all

    【讨论】:

      【解决方案2】:

      您可以使用 Promise.all 通过一次调用获取您的 API 并等待承诺得到解决

      setLoading(true);
      const promise1 = callAPI();
      const promise2 = callAPI();
      const promise3 = callAPI();
      
      Promise.all([promise1, promise2, promise3]).then((values) => {
        console.log(values);
        setLoading(false)
      });
      

      如果你想处理 API 失败调用

      Promise.all([promise1.catch((error) => error), promise2.catch((error) => error),promise3.catch((error) => error)])
      .then(
        (values) => {
          console.log(values[0]); 
          console.error(values[1]); 
          console.error(values[2]); 
        }
      );
      

      【讨论】:

      • 如果任何 API 调用失败如何处理,
      • @MuhammadJaan 检查编辑后的答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 2013-04-10
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2020-11-26
      • 2021-01-16
      相关资源
      最近更新 更多