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; }}