【问题标题】:Google sign button dissapears when i refresh - React刷新时谷歌签名按钮消失 - 反应
【发布时间】:2017-12-14 01:15:43
【问题描述】:

登录按钮仅在服务器启动时有效,但一旦我在浏览器上刷新,登录按钮就消失了,并且此错误消息显示:

Error picture

当我在控制台中使用 firefox 时,它显示 window.gapi 未定义

我不确定为什么会发生此错误,如果您能提供帮助,我将不胜感激 :) 谢谢。

Uncaught TypeError: Cannot read property 'signin2' of undefined
    at App.renderGoogleSignInButton (index_bundle.js:32253)
    at App.componentDidMount (index_bundle.js:32216)

这是我的反应代码:

import React, { Component } from 'react';

export default class App extends Component {
constructor(props){
  super(props)
 this.signOut = this.signOut.bind(this)
}
componentDidMount() {
    window.addEventListener('google-auth-loaded',
    this.renderGoogleSignInButton());


}

signOut() {
var auth2 = window.gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
  console.log('User signed out.');
});


}

onSignIn(googleUser) {

   var auth2 = window.gapi.auth2.getAuthInstance();

    console.log(googleUser.getAuthResponse().id_token)
    var profile = googleUser.getBasicProfile();
    console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
  }

renderGoogleSignInButton() {
    window.gapi.signin2.render('my-signin2', {
      'scope': 'email',
        'theme': 'light',
        'longtitle': true,
        'onsuccess': this.onSignIn,
        'onfailure': this.onSignInFailure
    });
}


onSignInFailure(error) {
    console.error(error);
}

render() {
    return (
        <div>
        <button onClick={this.signOut}>logout</button>            
        <div id='my-signin2'></div>
        </div>
    );
  }
}

我的 html :)

<meta name="google-signin-client_id" xxxxxxxxxx.apps.googleusercontent.com">
<div class="" id="app"></div>
  <script src="https://apis.google.com/js/platform.js?onload=triggerGoogleAuthLoaded" async defer></script>
  <script>
    function triggerGoogleAuthLoaded() {
      window.dispatchEvent(new Event('google-auth-loaded'));
    }
  </script>

解决此问题的两种方法: 1 从 html 脚本中删除异步延迟 2 去掉 () 所以它看起来像这样 window.addEventListener('google-auth-loaded',this.renderGoogleSignInButton); 所以它不会立即触发

【问题讨论】:

  • 感谢您的解决方案。删除异步延迟修复它。

标签: javascript reactjs google-api google-signin google-oauth


【解决方案1】:

页面重新加载后,由于库未完全加载,会发生这种情况。

只需使用 setTimeout 进行调试。

setTimeout(() => {this.renderGoogleSignInButton()}, 1000);

增加时间限制值。像 5000 。检查可能是库加载问题。

【讨论】:

  • 根本不是解决方案
猜你喜欢
  • 2018-07-01
  • 2016-02-13
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2018-11-16
  • 2020-09-01
  • 2015-10-15
相关资源
最近更新 更多