开发者问题收集

React 中的 Google Auth

2019-02-08
776

当我在 React 中实现 google auth 时,出现以下错误(如下图所示)。

TypeError: window.gapi.init is not a function
(anonymous function)
src/components/GoogleAuth.js:8
   5 | class GoogleAuth extends Component {
   6 |   componentDidMount() {
   7 |     window.gapi.load("client:auth2", () => {
>  8 |       window.gapi
   9 |         .init({
  10 |           clientId:
  11 |             "258474052449-

代码:

  componentDidMount() {
    window.gapi.load("client:auth2", () => {
      window.gapi
        .init({
          clientId:
            "258474052449-vs1334g29cemopfhplff5nqe5l2vshac.apps.googleusercontent.com",
          scope: "email"
        })
        .then(() => {
          window.gapi.client
            .request({
              path:
                "https://people.googleapis.com/v1/people/me?requestMask.includeField=person.names"
            })
            .then(() => {
              this.auth = window.gapi.auth2.getAuthInstance();
              this.onAuthChange(this.auth.isSignedIn.get());
              this.auth.isSignedIn.listen(this.onAuthChange);
            });
        });
    });
  }

Screenshoot

2个回答

Google API 文档 显示 init 函数是在 client 对象上定义的。

您的 window.gapi.init 应该是 window.gapi.client.init

Vivek
2019-02-08

首先需要在react的html文件中添加这个脚本:

<script src="https://accounts.google.com/gsi/client" async defer></script>, 
{ useEffect, useRef } from 'react';

import swal from 'sweetalert';
const Logingoogle = () => {
 
    const buttonContainerRef = useRef(null);

    useEffect(() => {
        const handleCredentialResponse = (response) => {
            console.log(response.credential);
        };

        const initGoogleSignIn = () => {
            if (window.google?.accounts?.id) {
                window.google.accounts.id.initialize({
                    client_id: "Your Client ID",
                    callback: handleCredentialResponse
                });

                if (buttonContainerRef.current) {
                    window.google.accounts.id.renderButton(
                        buttonContainerRef.current,
                        { theme: "outline", size: "large" }
                    );
                }
            } else {
                setTimeout(initGoogleSignIn, 500);
            }
        };

        initGoogleSignIn();
    }, []);

    
    return (
        <div>
            <div ref={buttonContainerRef}></div>
        </div>
    );
};
export default Logingoogle;
anurag yadav
2023-07-24