React:在页面加载时加载gapi和currentUser

时间:2017-11-21 19:49:44

标签: javascript reactjs

如果用户登录或未登录,我会尝试在页面加载时设置重定向。

我初始化gapi的HTML文件:

    <script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
        <script>
            function start() {
                console.log('script running')
                gapi.load('auth2', function() {
                    auth2 = gapi.auth2.init({
                        client_id: '817677528939-dss5sreclldv1inb26tb3tueac98d24r.apps.googleusercontent.com',
                        scope: 'profile email'
                    });
                });
            }
        </script> 

用户登录Login.js

/* global gapi */

import React from 'react';

import { Redirect } from 'react-router';
import AppBar from 'material-ui/AppBar';
import $ from 'jquery'


class Login extends React.Component{
    constructor(props) {
        super(props)
        this.handleSignIn = this.handleSignIn.bind(this)
        this.signInCallback = this.signInCallback.bind(this)
    }

    handleSignIn() {
        console.log(gapi.auth2)
        var x = gapi.auth2.getAuthInstance().grantOfflineAccess()
        console.log(x)
    }

    render() {
        return(
            <div>
                <AppBar className='appBar' title="Pliny" showMenuIconButton={false} zDepth={2} />
                <button  id="signinButton" onClick={this.handleSignIn} >Sign in with Google</button>

            </div>
        )
    }
}

class SignIn2 extends React.Component{

    constructor(props){
        super(props);
        this.updateRedirect = this.updateRedirect.bind(this)
        this.state = {
            redirect: false,
            loaded: false
        }
    }

    updateRedirect() {
        this.setState({
            redirect: true
        })
    }

    componentDidMount() {
        gapi.load('auth2', () => {
            gapi.auth2.init({
                client_id: '817677528939-dss5sreclldv1inb26tb3tueac98d24r'
            }).then((auth2) => {
                console.log( "signed in: " + auth2.isSignedIn.get())
                this.setState({
                    redirect: auth2.isSignedIn.get(),
                    loaded: true
                }, () => {console.log('this finished')})
            })
        })
    }

    render() {
        if (!this.state.loaded){
            console.log(this.state.loaded)
            return null
        }

        console.log(this.state.loaded)
        return (
            this.state.redirect ?
            <Redirect to='/options' /> : <Login updateRedirect = {this.updateRedirect} />
        )
    }    
}

export default SignIn2

我有一个重定向设置来处理登录(这里没有问题)。

但是,我现在在/options页面上遇到了问题。

Options.js

    componentDidMount() {    
        gapi.load('auth2', () => {
            var googleAuth = gapi.auth2.getAuthInstance()
            console.log(googleAuth)
        })

当页面最初重定向时,googleAuth会打印出值

jF {zd: {…}, aea: "single_host_origin", Ofa: true, d2: true, Z1: undefined, …}

但是,当我刷新页面时,它现在打印为null

为什么呢?

其次,我有一个打印出gapi信息的按钮:

checkUserData() {
    var googleAuth = gapi.auth2.getAuthInstance()
    console.log( "signed in: " + googleAuth.isSignedIn.get())
    var user = googleAuth.currentUser.get()
    console.log(user)
}

当我按下运行checkUserData()的按钮时,它会打印出我所期望的用户数据。

那么,为什么componentDidMount在刷新页面时会打印出null?我仍然登录,可以从按钮访问用户数据。

3 个答案:

答案 0 :(得分:0)

getAuthInstance要求在使用前调用init。我的假设是Google API会将您的身份验证会话存储在本地存储中(您在浏览器中进行检查),这就是您可以使用checkUserData()方法的原因。但是在页面刷新时,没有调用init函数,因此auth实例为null。

答案 1 :(得分:0)

您正在向index.html文件中添加很多JavaScript逻辑,这可能会使您感到困惑,因为您必须在index.htmlOptions.js和{ {1}}。

请为您的Login.js考虑以下内容:

index.html

完成,关闭该文件,再也不会引用它。

接下来,对于您的一个或多个JS文件,您需要以下内容:

<script src="https://apis.google.com/js/api.js"></script>

现在,通过练习在Chrome控制台中进行登录和注销,确保上面的方法对您有效。

控制台中的

import React from "react"; class someClassComponentYouDecideOn extends React.Component { componentDidMount() { window.gapi.load("client:auth2", () => { window.gapi.client.init({ clientId: "1234567890-abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com", scope: "email" }); }); } 将为您提供gapi.auth2.getAuthInstance()对象的属性,您会看到authsignIn是它拥有的许多属性中的两个,您可以通过:

signOutgapi.auth2.getAuthInstance().signIn()

当然要在浏览器上查看结果,您可能需要创建一个具有if条件的助手功能,您可以将其呈现给浏览器,如下所示:

gapi.auth2.getAuthInstance().signOut()

renderAuthButton() { if (this.state.isSignedIn === null) { return <div>I dont know if I am signed in</div>; } else if (this.state.isSignedIn) { return <div>I am signed in!</div>; } else { return <div>I am not signed in</div>; } } render() { return <div>{this.renderAuthButton()}</div>; } } 不是组成的,它也是isSignedIn库中auth对象的属性之一。

一旦您对此进行了验证,就可以像这样处理Promise:

gapi

答案 2 :(得分:0)

您可以尝试使用我的软件包:gapi-script,此软件包以正确的方式提供了gapi函数,因此您不必等待脚本加载。

也请查看此示例,它确实可以完成您要尝试的操作,example that checks if user is logged in or not, with gapi-script

Checking user google session

import React, { Component } from 'react';
import { gapi, loadAuth2 } from 'gapi-script'

import UserCard from './UserCard';
import './GoogleLogin.css';

class GoogleLogin extends Component {
    constructor(props) {
        super(props);
        this.state = {
            user: null
        }
    }
    async componentDidMount() {
        let auth2 = await loadAuth2(process.env.REACT_APP_CLIENT_ID, '')
        if (auth2.isSignedIn.get()) {
            this.updateUser(auth2.currentUser.get())
        } else {
            this.attachSignin(document.getElementById('customBtn'), auth2);
        }
    }
    async componentDidUpdate() {
        if(!this.state.user) {
            let auth2 = await loadAuth2(process.env.REACT_APP_CLIENT_ID, '')
            this.attachSignin(document.getElementById('customBtn'), auth2);
        }
    }
    updateUser(currentUser) {
        let name = currentUser.getBasicProfile().getName()
        let profileImg = currentUser.getBasicProfile().getImageUrl()
        this.setState({
            user: {
                name: name,
                profileImg: profileImg
            }
        })
    }
    attachSignin(element, auth2) {
        auth2.attachClickHandler(element, {},
            (googleUser) => {
                this.updateUser(googleUser);
            }, (error) => {
                console.log(JSON.stringify(error))
            });
    }
    signOut = () => {
        let auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(() => {
            this.setState({ user: null })
            console.log('User signed out.');
        });
    }
    render() {
        if(this.state.user) {
            return (
                <div className="container">
                    <UserCard user={this.state.user} />
                    <div id="" className="btn logout" onClick={this.signOut}>
                        Logout
                    </div>
                </div>
            );
        } else {
            return (
                <div className="container">
                    <div id="customBtn" className="btn login">
                        Login
                    </div>
                </div>
            );
        }
    }
}

export default GoogleLogin;