Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何通过在React.js中更改动态值来停止递归函数_Javascript_Reactjs_Typescript_React Hooks - Fatal编程技术网

Javascript 如何通过在React.js中更改动态值来停止递归函数

Javascript 如何通过在React.js中更改动态值来停止递归函数,javascript,reactjs,typescript,react-hooks,Javascript,Reactjs,Typescript,React Hooks,我正在调用verifyAuthentication函数,我希望调用该函数直到没有抛出错误,但有些情况下我希望它动态停止,但我没有实现这一点 const callback = (object, error) => { if (error) { if (error === 'out of retries') { setRetry(0); return; } } if (object.data) { Co

我正在调用
verifyAuthentication
函数,我希望调用该函数直到没有抛出错误,但有些情况下我希望它动态停止,但我没有实现这一点

const callback = (object, error) => {
    if (error) {
      if (error === 'out of retries') {
        setRetry(0);
        return;
      }
    }
    if (object.data) {
      Cookies.set('token', object.data.token, { expires: 60000 });
      setIsAuthenticated(true);
      Router.push('/extrato').then(() => {
        setIsInLoginStep(true);
      });
    }
  };

  const verifyAuthentication = (
    sessionKey: string,
    _retries: number,
    cb: AuthContextInterface['callback'],
  ) => {
    console.log('Continuar Verificando', keepVerifying);
    if (keepVerifying) {
      api
        .post(`${API_ENDPOINT}/session/verify`, {
          sessionId: sessionKey,
        })
        .then((res) => {
          if (res.status === 200) {
            cb(res, null);
          } else if (_retries > 0) {
            const newRetry = _retries - 1;
            setTimeout(() => {
              verifyAuthentication(sessionKey, newRetry, cb);
            }, delay);
          } else {
            callback([], 'out of retries');
          }
        })
        .catch(() => {
          if (_retries > 0) {
            const newRetry = _retries - 1;
            setTimeout(() => {
              verifyAuthentication(sessionKey, newRetry, cb);
            }, delay);
          } else {
            callback([], 'out of retries');
          }
        });
    }
  };
我只是简单地将
keepVerifying
状态更改为false,但在我的日志中,仍然将其视为true,非常确定这是因为它是一个递归函数

onClick={() => { setKeepVerifying(false) }}

关于如何实现这一点的任何提示?

每当调用
verifyAuthentication
时,其递归调用将始终使用与初始
verifyAuthentication
相同的闭包;
keepVerifying
(很可能是用
const
声明的)在该闭包中不会更改

一个选项是使用state指示下一次装载时是否应运行另一个调用
verifyAuthentication
,例如:

const [verifyAuthNextMount, setVerifyAuthNextMount] = useState(false);
useEffect(() => {
  if (verifyAuthNextMount) {
    setVerifyAuthNextMount(false);
    verifyAuthentication();
  }
}, [verifyAuthNextMount]
// Then, inside verifyAuthentication, instead of an immediate recursive call:
setVerifyAuthNextMount(true);
这将确保任何给定的
verifyAuthentication
运行都会引用
keepVerifying
的最新值

另一个选项是使用ref而不是state来进行
keepVerifying
,因为在所有渲染中都有一个稳定的引用

const keepVerifyingRef = useRef(true);
// ...
// inside verifyAuthentication:
if (keepVerifyingRef.current) {
  api
    .post( // ...
}
// click handler:
onClick={() => { keepVerifyingRef.current = false; }}