繁体   English   中英

加载 React 组件时未定义 gapi

[英]gapi is not defined when loading React Component

我正在尝试使用 React 集成 Google 登录(链接)。
我发现了一个过去解决了这个问题的问题Using google sign in button with react 2

我复制了与上述相同的步骤。 在我的index.html我做

<script src="https://apis.google.com/js/platform.js?onload=triggerGoogleLoaded" async defer></script>
    <script type="text/javascript">
        function triggerGoogleLoaded() {
            console.log("google event loaded");
            window.dispatchEvent(new Event('google-loaded'));
        }
    </script>

然后我的Component看起来像

var LoginButton = React.createClass({

    onSignIn: function(googleUser) {
        console.log("user signed in"); // plus any other logic here
    },

    renderGoogleLoginButton: function() {
        console.log('rendering google signin button');
        gapi.signin2.render('my-signin2', {
            'scope': 'https://www.googleapis.com/auth/plus.login',
            'width': 200,
            'height': 50,
            'longtitle': true,
            'theme': 'light',
            'onsuccess': this.onSignIn
        })
    },

    componentDidMount: function() {
        window.addEventListener('google-loaded',this.renderGoogleLoginButton);
    },

    render: function() {
        let displayText = "Sign in with Google";
        return (
            <div class="g-signin2" data-onsuccess="onSignIn"></div>
        );
    }

});

export default LoginButton;

当我使用yarn start运行程序yarn start ,我得到

/Users/Harit.Himanshu/bl/sources/webs/google-login/src/LoginButton.js
  11:9   error    'gapi' is not defined                             no-undef
  26:13  warning  'displayText' is assigned a value but never used  no-unused-vars

✖ 2 problems (1 error, 1 warning)

完整的源代码可在https://github.com/hhimanshu/google-login-with-react 获得

有人可以帮我理解我的错误吗?

谢谢

在我看来,您正在将 google api 作为脚本标记加载,我们希望将window.gapi设置为 google api。 但是,您正在运行 eslint 或其他一些检查器,并且不知道window.gapi应该存在。 它失败了,因为它看到您使用了未声明的变量。

一个廉价的解决方法是告诉 Eslint 你知道你在做什么;

/* global gapi */

你应该在你的文件和eslint顶部将把gapi为已知的全局变量。

这对我有用。 把它放在 componentDidMount 或构造函数中:

componentDidMount() {
    window.gapi.load('auth2', () => {
        // Retrieve the singleton for the GoogleAuth library and set up the client.
        this.auth2 = window.gapi.auth2.init({
            client_id: '436676563344-.apps.googleusercontent.com',
            cookiepolicy: 'single_host_origin',
        });

        this.auth2.attachClickHandler(this.refs.googleButton, {},
            (googleUser) => {
                this.googleLogin(googleUser.getBasicProfile());
            }, (error) => {

            });
    });
}

你也可以试试包gapi-script ,这个包立即提供了 gapi,所以你不必等待任何脚本加载,只需导入它并使用:

import { gapi } from 'gapi-script';

确保您没有使用异步延迟,这会导致 window.gapi.someMethod() 和脚本加载之间的竞争条件

简而言之,从 index.html 中的脚本标记中删除async defer

<script src="https://apis.google.com/js/platform.js?onload=triggerGoogleLoaded" async defer></script>

<script src="https://apis.google.com/js/platform.js?onload=triggerGoogleLoaded"></script>

我有一个类似的问题。

我使用 'react-snap' 进行 SEO。 它阻止我使用'gapi'。 我找到了 navigator.userAgent 'ReactSnap'。

if (navigator.userAgent !== 'ReactSnap') {
    // some code to dynamically load a script
    let myScript = document.createElement('script')
    myScript.setAttribute('src', 'https://apis.google.com/js/platform.js')
    document.body.appendChild(myScript)
}

我解决了一个问题。 它运作良好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM