javascript - Google 登录:无法访问 GoogleAuth 对象
问题描述
我正在尝试将 Google 登录添加到我的网络应用程序。gapi.auth2.init() 成功,当我将 GoogleAuth 定义为 gapi.auth2.getAuthInstance() 时,它不会引发错误。但是,当我尝试运行 GoogleAuth.signIn() 时,它抱怨它不是一个函数。我究竟做错了什么?
这一切都在一个功能性的 React 组件中:
let GoogleAuth
const googleSignIn = () => {
GoogleAuth.signIn()
.then(() => {
console.log('signed in')
})
.catch(err => {
console.log('failed to sign in: ')
console.log(err)
})
}
window.gapi.load('auth2', () => {
gapi.auth2.init({
client_id: googleClientId
})
.then(() => {
console.log('google auth initialized') // This shows in the console
GoogleAuth = gapi.auth2.getAuthInstance() // This does not throw an error
}, err => {
console.log('google auth failed to initialize')
console.log(err)
})
})
return <GoogleLoginButton text="Log in with Google" onClick={googleSignIn} />
我等到看到“google auth initialized”消息,然后单击按钮,但它会引发如上所述的错误。
解决方案
事实证明 gapi.auth2.getAuthInstance() 返回一个承诺,而不是一个对象(与文档相反,感谢 Google),所以我只需要这样做:
gapi.auth2.getAuthInstance()
.then(instance => {
GoogleAuth = instance
}, err => {
console.log(err)
})
现在它起作用了!
推荐阅读
- css - 大网格css没有图片显示
- java - 为什么将“0000:00:00 00:00:00”解析为日期返回-0001-11-28T00:00:00Z?
- jquery - 如何使用来自 API 的 JSON 填充选择列表?
- swiftui - 从 ActionSheet 删除时 ForEach 不更新
- android - 如何设置在 BottomAppBar 隐藏/显示时触发的侦听器?
- android - 代码重复错误 - 两个库包含相同的类 - Gradle、Android Studio
- java - 如何使用 Java 中的 Discord JDA 在 Discord 上的特定时间发送消息
- css - 如何使用角度设置 SCSS 变量
- java - Selenium 如何使用@FindBy 关闭通知警报?
- javascript - React UseContext 更改不重新渲染组件