我是ReactJS的新手,我正在尝试使用ReactJS应用程序进行Google登录,但遇到的问题是,当我单击Google登录按钮时,googleLogin函数会调用多次并响应多次。
我正在尝试通过绑定按钮单击事件来解决此问题,但这会影响我的代码并提出任何解决方案。
import React, { Component } from 'react';
import google from './google.png'
import config from '../config';
class GoogleLogin extends Component{
constructor(props) {
super(props)
}
componentDidMount(){
(function() {
var e = document.createElement("script");
e.type = "text/javascript";
e.async = true;
e.src = "https://apis.google.com/js/client:platform.js?onload=gPOnLoad";
var t = document.getElementsByTagName("script")[0];
t.parentNode.insertBefore(e, t)
})();
}
//Triggering login for google
googleLogin = () => {
let response = null;
window.gapi.auth.signIn({
callback: function(authResponse) {
this.googleSignInCallback( authResponse )
}.bind( this ),
clientid: config.google, //Google client Id
cookiepolicy: "single_host_origin",
requestvisibleactions: "http://schema.org/AddAction",
scope: "https://www.googleapis.com/auth/plus.login email"
});
}
googleSignInCallback = (e) => {
console.log( e )
if (e["status"]["signed_in"]) {
window.gapi.client.load("plus", "v1", function() {
if (e["access_token"]) {
this.getUserGoogleProfile( e["access_token"] )
} else if (e["error"]) {
console.log('Import error', 'Error occured while importing data')
}
}.bind(this));
} else {
console.log('Oops... Error occured while importing data')
}
}
getUserGoogleProfile = accesstoken => {
var e = window.gapi.client.plus.people.get({
userId: "me"
});
e.execute(function(e) {
if (e.error) {
console.log(e.message);
console.log('Import error - Error occured while importing data')
return
} else if (e.id) {
//Profile data
alert("Successfull login from google : "+ e.displayName )
console.log( e );
return;
}
}.bind(this));
}
render(){
return(
<img src={google} title="google login" alt="google" onClick={ () => this.googleLogin() }/>
)
}
}
export default GoogleLogin;