reactjs - 将基于类的组件转换为 Hook (gapi API)

标签 reactjs react-hooks google-api-js-client

我有一个基于类的组件,它使用 gapi (Google Auth) API 呈现一个按钮并且它可以工作:

import React from 'react';

class GoogleAuth extends React.Component {
  state = { isSignedIn: null };

  componentDidMount() {
    window.gapi.load('client:auth2', () => {
      window.gapi.client
        .init({
          clientId: process.env.REACT_APP_CLIENT_ID,
          scope: 'email',
        })
        .then(() => {
          this.auth = window.gapi.auth2.getAuthInstance();
          this.handleAuthChange();
          this.auth.isSignedIn.listen(this.handleAuthChange);
        });
    });
  }

  handleAuthChange = () => {
    this.setState({ isSignedIn: this.auth.isSignedIn.get() });
  };

  handleSignIn = () => {
    this.auth.signIn();
  };

  handleSignOut = () => {
    this.auth.signOut();
  };

  renderAuthButton() {
    if (this.state.isSignedIn === null) {
      return null;
    } else if (this.state.isSignedIn) {
      return <button onClick={this.handleSignOut}>Sign Out</button>;
    } else {
      return <button onClick={this.handleSignIn}>Sign in with Google</button>;
    }
  }

  render() {
    return <div>{this.renderAuthButton()}</div>;
  }
}

export default GoogleAuth;

我很难尝试将其转换为使用 Hook 。主要问题是 this.auth...这就是类如何引用 window.gapi.auth2.getAuthInstance()

我已经尝试了很多不同的方法,包括将身份验证保持在以下状态:

export default function GoogleAuth() {
    const [isSignedIn, setIsSignedIn] = useState(null);
    const [auth, setAuth] = useState(null);
    useEffect(() => {
        window.gapi.load('client:auth2', () => {
            window.gapi.client
                .init({
                    clientId: process.env.REACT_APP_CLIENT_ID,
                    scope: 'email',
                })
                .then(() => {
                    setAuth(window.gapi.auth2.getAuthInstance());
                    setIsSignedIn(auth.isSignedIn.get());
                    auth.isSignedIn.listen(() => setIsSignedIn(auth.isSignedIn.get()));
                });
        });
    }, [auth]);

最佳答案

仅仅 8 个月后,请像下面那样尝试使用带有身份验证的 useRef。它对我有用。

   const GoogleAuth  = () => {
      const [isSignedIn, setSignedIn] = useState(null)
      const auth = useRef(null);
      useEffect(() => {
        window.gapi.load('client:auth2', () => {
          window.gapi.client.init({
            clientId:
              'jcu.apps.googleusercontent.com',
            scope: 'email'
          }).then(() => {
            auth.current = window.gapi.auth2.getAuthInstance();
            setSignedIn(auth.current.isSignedIn.get());
            auth.current.isSignedIn.listen(onAuthChange)
          });
        });
      }, [isSignedIn]);
    
     const onAuthChange = () => {
          setSignedIn(auth.current.isSignedIn.get())
      }
    
     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>);
      }
    }

关于reactjs - 将基于类的组件转换为 Hook (gapi API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55961293/

相关文章:

javascript - 使用 Google API 进行身份验证后无法获取访问和刷新 token

reactjs - 为什么我会收到此错误 : Invalid hook call. Hooks can only be called inside of a function component/

angularjs - 如何将 gmail api 正确加载到 angular 2 应用程序

javascript - 如何使用特定数组索引更改状态数组的对象值

javascript - 通过具有重复键的另一个数组过滤对象数组

reactjs - React 状态不会立即随 useState 更新

string - typescript - 逗号运算符的左侧未使用且没有副作用 - 如何在 hookrouter 的路由中使用常量代替字符串?

javascript - 如何使用gapi在Angular 9中发送电子邮件

javascript - 在 onChange (ReactJS) 中获取 2 个组合日期选择器的值

javascript - 来自对象数组的 React redux 计数器示例