【问题标题】:Recursive method is calling again and again递归方法是一次又一次的调用
【发布时间】:2022-08-18 05:53:11
【问题描述】:
    const callAFunction = () => {
      if (AppState.currentState === \'background\') {
        function1()
      }
    }

    useEffect(()=>{
AppState.addEventListener(\'change\', callAFunction);
    },[])
    const function1 = () => {
      axios.get(\'/user_login\', {
        params: {
          username: \'john1904\',
        }
      })
        .then(function (response) {
          if (response.data.status === false) {
            function1()
          }
    
        })
    }

我正在递归地使用上述函数。但是随着应用程序进入后台,function1 一次又一次地调用,因为我已经调用了 function1()。所以我希望每次应用程序进入后台时调用 function1() 。但是在异步形式中,就像 function1() 一样,它不会再次调用它。

因此,当应用程序处于后台时,我无法了解如何执行此操作,因此它将检查此功能是否正在运行,然后不要运行它,否则请运行它。

    标签: android ios react-native background


    【解决方案1】:

    现在,如果statusfalse,那么请求之间的唯一时间就是Axios 调用端点的时间。这可能是非常短的时间(比如几毫秒)。如果要轮询直到获得 statustrue,请为请求设置超时。

    // ...
    .then(function (response) {
      if (response.data.status === false) {
        setTimeout(function1, 1000);
      }   
    })
    

    上面的示例在请求之间需要 1 秒。您可以调整1000 以满足您的需要。

    有关超时和 React 组件的常见问题,另请参阅此问题:Can't perform a React state update on an unmounted component

    【讨论】:

      猜你喜欢
      • 2018-02-06
      • 1970-01-01
      • 2010-09-28
      • 2016-05-26
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      相关资源
      最近更新 更多