gpt4 book ai didi

javascript - 当移动重新捕获就绪回调时,React 会抛出 COR 错误

转载 作者:行者123 更新时间:2023-11-28 03:15:50 25 4
gpt4 key购买 nike

我有一个使用 create-react-app 创建的 React 应用程序。我将 reCaptcha 放在上面,然后放入下面,一切都很好。 token 回来了,我可以嵌套一个获取并继续我的生活。

componentDidMount(){
if(!this.state.isRecaptchaReady){
window.grecaptcha.ready(function(){
window.grecaptcha.execute('id', {action: 'homepage'})
.then(//...)
});
}
}

但我不能,因为我知道必须有更好的方法。我想获取 token 并存储它,然后调用一个函数,而不是嵌套得太深,我无法得到 this 来拯救我的生命(我的意思是我可以,但不想用一堆绑定(bind))。

requestRecaptchToken = () => {
console.log(window.grecaptcha);
//const tokenPromise = window.grecaptcha.execute('id', {action: 'homepage'});
}

handleRecaptchToken = data => {
const { modal } = this.state;
modal.recaptcha = JSON.parse(data);
this.setState({modal});
}

componentDidMount(){
if(!this.state.isRecaptchaReady){
window.grecaptcha.ready(this.handleRecaptchReady());
}
}

componentDidUpdate(){
if(this.state.isRecaptchaReady){
this.requestRecaptchToken();
}
}

这一行

const tokenPromise = window.grecaptcha.execute('id', {action: 'homepage'});

外部

window.grecaptcha.ready()

爆炸

Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/docs/cross-origin-errors.html for more information.

问题是它没有意义,我读了一些 WebPack eval 的东西,但这似乎有点超出了我目前的学习曲线。

最佳答案

React 抛出的消息主要是因为我没有捕获错误并且它不知道在哪里查找。我仍然不知道为什么在 ready 之外调用 execute 会出现错误,但我认为调用方法、渲染和 React 可以访问的内容之间存在竞争条件。这完全是猜测,我还不知道如何证明它。

然而,在退一步思考我的目标后,我确实解决了这个问题。我没有将其分解为多个方法(我的 java 大脑妨碍了),而是简单地使用箭头函数将 this 作用域绑定(bind)到组件。

try {
window.grecaptcha.ready(() => {
window.grecaptcha.execute(process.env.REACT_APP_RECAPTCHA_ID).then(data => {
this.handleRecaptchToken(data);
});
});
} catch(e) {
console.log("reCaptcha token load error: " + e);
}

由于 setState 可以采用可选回调方法作为第二个参数,因此 handleRecaptchToken 可以在 token 数据完成后获取数据。

handleRecaptchToken = data => {
this.setState({"recaptchaToken" : data}, this.fetchRecaptchaData);
}

fetchRecaptchaData 然后对我的服务器进行 api 调用以获取 google 数据并再次更新状态。

关于javascript - 当移动重新捕获就绪回调时,React 会抛出 COR 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59657457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com