登录按钮仅在服务器启动时起作用,但是当我在浏览器中刷新时,登录按钮就消失了,并且此错误消息显示:

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>


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

最佳答案

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

只需使用setTimeout进行调试即可。

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


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

10-06 08:21