Javascript 在实现google oauth 2.0隐式登录时,isSignedIn的侦听器被多次触发
我遇到的问题是Javascript 在实现google oauth 2.0隐式登录时,isSignedIn的侦听器被多次触发,javascript,reactjs,google-oauth,Javascript,Reactjs,Google Oauth,我遇到的问题是 auth.isSignedIn.listen((isLoggedIn) => ... 函数在init()中多次触发。当我在不刷新的情况下登录和注销时,它触发的次数不断增加。我在下面添加了控制台日志图像。消息“多少次”只应打印一次 下面是我的程序文件 app.js import React, { Component } from 'react' import logo from './logo.svg' import './App.css' import GoogleOa
auth.isSignedIn.listen((isLoggedIn) => ...
函数在init()中多次触发。当我在不刷新的情况下登录和注销时,它触发的次数不断增加。我在下面添加了控制台日志图像。消息“多少次”只应打印一次
下面是我的程序文件
app.js
import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
import GoogleOauth from './components/googleOauth.js'
class App extends Component {
constructor (props) {
super(props)
this.state = {
isLoggedin: false
}
this.logoutFunc = this.logoutFunc.bind(this)
this.init = this.init.bind(this)
this.signin = this.signin.bind(this)
}
logoutFunc () {
console.log('clicked logout')
window.gapi.load('auth2', () => {
const auth = window.gapi.auth2.getAuthInstance()
auth.signOut()
this.setState({
isLoggedin: !this.state.isLoggedin
})
})
}
loadScript () {
const script = document.createElement('script')
script.src = 'https://apis.google.com/js/client:platform.js'
script.onload = this.init
script.id = 'google-login'
document.head.appendChild(script)
}
componentWillMount () {
console.log('is it the componentWillMount')
this.loadScript()
}
signin () {
console.log('clicked signin')
this.init()
this.logoutFunc()
}
init () {
window.gapi.load('auth2', () => {
const auth = window.gapi.auth2.getAuthInstance()
auth.isSignedIn.listen((isLoggedIn) => {
const profile = auth.currentUser.get().getBasicProfile()
if (isLoggedIn) {
console.log('how many times')
}
})
})
}
render () {
return (
<div className='App'>
<header className='App-header'>
<img src={logo} className='App-logo' alt='logo' />
<h1 className='App-title'>Welcome to React</h1>
</header>
<p className='App-intro'>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<GoogleOauth logoutFunc={this.logoutFunc} signin={this.signin} />
</div>
)
}
}
export default App
googleOauth.js
import React from 'react'
const GoogleOauth = ({logoutFunc, signin}) => {
return (
<div>
<div className='g-signin2' data-onsuccess='onSignIn' onClick={signin} data-width='94' data-height='36' />
<button onClick={logoutFunc}> logout </button>
</div>
)
}
export default GoogleOauth
从“React”导入React
const GoogleOauth=({logoutFunc,signin})=>{
返回(
注销
)
}
导出默认GoogleOauth
您多次调用init(从而多次添加侦听器)。添加一个变量来检查它是否已经被调用,在这种情况下跳过它。实际上init()没有多次被调用。在侦听器之前,我在init中添加了一个控制台日志。init()只被调用一次,但是监听器记录了多次。噢!我现在明白你的意思了。忽略我之前的评论。单击“登录”按钮时,我不需要初始化()。它正在附加另一个侦听器。