本文介绍了加载React Component时未定义gapi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试整合Google登录( )使用React。

我发现一个问题已经解决了这个问题

I am trying to integrate Google Sign In (link) using React.
I found a question that has solved this in past Using google sign in button with react 2

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

I replicated the same steps as mentioned. In my index.html I do

<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>

然后我的组件看起来像

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;

当我使用纱线开始运行程序 ,我得到

/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)

完整的源代码位于

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

Could someone please help me understand my mistake?

谢谢

推荐答案

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

It looks to me like you're loading the google apis as a script tag, which we'd expect to set window.gapi to the google api. However, you're then running eslint or some other checker, and that has no idea that window.gapi is supposed to exist. It's failing because it sees you using an undeclared variable.

一个便宜的解决方法是告诉Eslint你知道自己在做什么;

A cheap fix is to tell Eslint that you know what you are doing;

/* global gapi */

把它放在你文件的顶部,eslint会将 gapi 视为已知的全局变量。

Put this at the top of your file and eslint will treat gapi as a known global variable.

这篇关于加载React Component时未定义gapi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 19:04