当另一个组件调用loginBefore函数时,我需要将返回的验证码令牌分配给captchaToken变量,但executeRecaptcha始终未定义,因此它执行if语句中的代码块。不知何故,我认为我需要等到executeRecaptcha函数初始化,然后调用getCaptchaToken函数。有什么好的方法可以做到这一点吗?感谢您的帮助。
import { useGoogleReCaptcha } from 'react-google-recaptcha-v3';
export const useAxiosClient = () => {
const navigate = useNavigate();
const { executeRecaptcha } = useGoogleReCaptcha();
const getCaptchaToken = async (action: string) => {
if (!executeRecaptcha) {
console.log('Execute recaptcha not yet available');
return;
}
return await executeRecaptcha(action);
};
const loginBefore = async () => {
const captchaToken = await getCaptchaToken('login');
我尝试在一定的延迟后调用 getCaptchaToken 函数,这有效,但并不总是有效,我认为这不是一个好的解决方案。
我使用了
react-google-recaptcha-v3
,这种行为让我感到非常困惑。
有一个新库为 react 实现了不可见的 reCAPTCHA,称为 @rusted/react-recaptcha-v3
它有内置的操作队列系统来关心这一点。 只需按照以下方式使用即可。
import {
useExecuteReCaptcha,
useSkipInjectionDelay,
} from '@rusted/react-recaptcha-v3'
export const useAxiosClient = () => {
const executeRecaptcha = useExecuteReCaptcha();
const loginBefore = async () => {
const captchaToken = await getCaptchaToken('login');
//other desired stuff
}
}
executeRecaptcha
功能始终可用。与 Google Recaptcha 令牌的承诺将尽快解决并加载 reCAPTCHA 脚本。
请注意! 用
ReCaptchaProvider
包裹你的父组件,否则 Promise 将被立即拒绝。
您可以检查此包的 GitHub 存储库它具有更清晰的源代码并实现了丰富的测试。
此外,请查看
injectionDelay
提供程序属性 + useSkipInjectionDelay
挂钩,以防您现在想要炸毁网站的 PageSpeed 分数。
如果有人从 Google 来到这里,我通过将我的 Recaptcha 高阶组件移至层次结构中更高的位置来解决此问题。我的猜测是这个组件永远不应该被重新渲染。