React中Google Identity登陆完成后不触发callback回调问题
问题核心原因
- 你通过
data-callback属性传递的是字符串handleCredentialResponse,Google Identity脚本会默认从全局window对象上查找该回调函数,但你在React组件内部定义的handleCredentialResponse是组件作用域内的局部函数,没有挂载到全局,Google脚本无法访问到,因此回调不会触发。 - 你提到的SameSite Cookie相关警告属于Google侧的Cookie配置提示,不会影响回调触发,可以忽略。
解决方案1:将回调挂载到全局window(最简单适配现有代码)
使用useEffect在组件挂载时将回调函数挂载到window,组件卸载时清除避免内存泄漏,修正后代码如下:
import { useEffect } from 'react'; function GoogleLogin() { const handleCredentialResponse = (response) => { console.log("called"); alert(response.credential); }; const responseGoogleFail = (response) => { console.log(response); }; useEffect(() => { // 挂载回调到全局 window.handleCredentialResponse = handleCredentialResponse; // 组件卸载时清理 return () => { delete window.handleCredentialResponse; } }, []) return ( <div> <div id="g_id_onload" data-client_id={process.env.REACT_APP_GOOGLECLIENTID} data-context="signin" data-ux_mode="popup" data-callback="handleCredentialResponse" data-auto_prompt="false" ></div> {/* React中使用className代替class属性 */} <div className="g_id_signin" data-type="standard" data-shape="pill" data-theme="outline" data-text="signin_with" data-size="large" data-logo_alignment="left" ></div> </div> ); }
解决方案2:使用JS API手动初始化(更符合React开发规范)
避免依赖全局挂载,直接调用Google Identity的JS API初始化,代码更可控:
import { useEffect } from 'react'; function GoogleLogin() { const handleCredentialResponse = (response) => { console.log("called"); alert(response.credential); }; useEffect(() => { // 确保google脚本已加载完成后初始化 if (window.google) { window.google.accounts.id.initialize({ client_id: process.env.REACT_APP_GOOGLECLIENTID, callback: handleCredentialResponse, context: 'signin', ux_mode: 'popup', auto_prompt: false }); // 渲染登录按钮 window.google.accounts.id.renderButton( document.getElementById('g_id_signin'), { type: 'standard', shape: 'pill', theme: 'outline', text: 'signin_with', size: 'large', logo_alignment: 'left' } ); } }, []) return ( <div> <div id="g_id_signin"></div> </div> ); }
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

