【问题标题】:Refactoring a class based component to hooks (gapi API)将基于类的组件重构为钩子(gapi API)
【发布时间】:2020-09-26 18:31:29
【问题描述】:

我正在尝试将基于类的组件重构为使用钩子的函数式组件。在尝试获取我的登录状态时,我陷入了在 gapi 中正确使用 useState 的问题。

只是想知道,我想得到什么:

1) 初始化后获取“auth”对象的引用

2) 弄清楚我当前是否已登录

3) 在屏幕上打印我的身份验证状态

这里已经提出了一个类似的问题:LINK 但不幸的是,我错过了将答案实施到我的案例中。

这是类组件:

import React from "react";

class GoogleAuth extends React.Component {
    componentDidMount() {
        window.gapi.load("client: auth2", () => {
            window.gapi.client
                .init({
                    clientId: "myVerySecretAPI",
                    scope: "email"
                })
                .then(() => {
                    this.auth = window.gapi.auth2.getAuthInstance(); //this gets me acces to the auth object
                    this.setState({ isSignedIn: this.auth.isSignedIn.get() });
                });
        });
    }

    renderAuthButton() {
        if (this.state.isSignedIn === null) {
            return <div>I dont know if we are 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>;
    }
}

export default GoogleAuth;

这是我重构的代码:

import React, { useEffect, useState } from "react";

const GoogleAuth = () => {
    const [ auth, setAuth ] = useState(null);

    useEffect(
        () => {
            window.gapi.load("client:auth2", () => {
                window.gapi.client
                    .init({
                        clientId: "834243588921-gob95b7q7n3eids3fm8du8oharkv5od0.apps.googleusercontent.com",
                        scope: "email"
                    })
                    .then(() => {
                        setAuth(window.gapi.auth2.getAuthInstance());
                        auth({ isSignedIn: setAuth.isSignedIn.get() }); // this is the line where I get an error (please see below)
                    });
            });
        },
        [ auth ]
    );

    const renderAuthButton = (isSignedIn) => {
        if (isSignedIn === null) {
            return <div>I dont know if we are signed in</div>;
        } else if (isSignedIn) {
            return <div>I am signed in!</div>;
        } else {
            return <div>I am not signed in</div>;
        }
    };

    return <div>{renderAuthButton()}</div>;
};

export default GoogleAuth;

我在 chrome 中收到一个错误,说:

Uncaught TypeError: Cannot read property 'get' of undefined at GoogleAuth.js:16

我知道,我遗漏了一些小东西来了解钩子的使用。 欢迎任何帮助!

【问题讨论】:

    标签: reactjs oauth oauth-2.0 react-hooks google-api-js-client


    【解决方案1】:

    所以你基本上是在保存几个项目。第一个是您从window.gapi.auth2.getAuthInstance() 获得的实际 身份验证实例,第二个是身份验证状态isSignedIn。在您的代码中,您使用实例setAuth,然后尝试调用保存的实例并将isSignedIn 作为键和状态设置器作为值的新对象传递给它。这行不通。

    您可以先获取实例,然后使用该实例从中获取身份验证状态以保存到您的状态中。您还应该使用一个空的依赖数组,以便在挂载GoogleAuth 时只运行一次效果。

    此外,您的 renderAuthButton 函数被定义为采用 isSignedIn 参数,但您没有在返回中传递任何内容。由于这是一个功能组件,尽管您可以简单地省略参数并在范围内使用状态值。

    const GoogleAuth = () => {
      const [isSignedIn, setIsSignedIn ] = useState(null);
    
      useEffect(
        () => {
          window.gapi.load("client:auth2", () => {
            window.gapi.client
              .init({
                clientId: "834243588921-gob95b7q7n3eids3fm8du8oharkv5od0.apps.googleusercontent.com",
                 scope: "email"
              })
              .then(() => {
                const authInstance = window.gapi.auth2.getAuthInstance();
                setIsSignedIn(authInstance.isSignedIn.get());
              });
          });
        },
        []
      );
    
      const renderAuthButton = () => {
        if (isSignedIn === null) {
          return <div>I don't know if we are signed in</div>;
        } else if (isSignedIn) {
          return <div>I am signed in!</div>;
        } else {
          return <div>I am not signed in</div>;
        }
      };
    
      return <div>{renderAuthButton()}</div>;
    };
    

    【讨论】:

      猜你喜欢
      • 2019-09-21
      • 2019-08-08
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 2020-12-21
      • 1970-01-01
      • 2020-05-18
      相关资源
      最近更新 更多