当另一个组件调用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');
Run Code Online (Sandbox Code Playgroud)
我尝试在一定的延迟后调用 getCaptchaToken 函数,该函数有效,但并不总是有效,我认为这不是一个好的解决方案。
小智 0
我使用过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
}
}
Run Code Online (Sandbox Code Playgroud)
executeRecaptcha功能始终可用。与 Google Recaptcha 令牌的承诺将在加载 reCAPTCHA 脚本后立即得到解决。
请注意!包装你的父组件,ReCaptchaProvider否则承诺将被立即拒绝。
您可以检查此包的 GitHub 存储库,它具有更清晰的源代码并实现了丰富的测试。
另外,如果您现在想提高网站的PageSpeed 分数,请查看injectionDelay提供程序属性 +挂钩。useSkipInjectionDelay
| 归档时间: |
|
| 查看次数: |
974 次 |
| 最近记录: |