如何在React中实现Google身份服务库?现有登录代码已失效
解决React谷歌登录组件失效问题
问题原因
你当前使用的react-google-login依赖的Google Sign-In JavaScript API已被官方弃用,取而代之的是Google Identity Services,这是组件停止工作的核心原因。
解决方案:迁移到@react-oauth/google
这是官方推荐的React谷歌登录封装库,适配最新的Google Identity Services。
1. 替换依赖包
卸载旧包,安装新依赖:
npm uninstall react-google-login npm install @react-oauth/google jwt-decode
jwt-decode用于解析谷歌返回的身份凭证,快速获取用户信息。
2. 配置全局OAuth Provider
在项目入口文件(如src/index.js)中添加全局Provider,传入你的Google客户端ID:
import { GoogleOAuthProvider } from '@react-oauth/google'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <GoogleOAuthProvider clientId="你的Google Cloud客户端ID"> <App /> </GoogleOAuthProvider> );
3. 修改Login组件代码
替换原有的GoogleLogin组件,调整回调逻辑:
import React, { Component } from "react"; import Auth from "../../helper/auth"; import PropTypes from "prop-types"; import logo from "../../img/logo.png"; import { Link } from "react-router-dom"; import { GoogleLogin } from '@react-oauth/google'; import jwt_decode from "jwt-decode"; class Login extends Component { onSuccess = (response) => { // 解析谷歌返回的JWT凭证,获取用户信息 const userInfo = jwt_decode(response.credential); Auth.setStorage(userInfo); this.props.getLoggedUser(userInfo.email); this.props.history.push("/home"); }; onFailure = (error) => { alert(error?.details || '登录失败,请重试'); }; // 替换已弃用的componentWillMount componentDidMount() { if (this.props.loggedUser != null) { this.props.history.push("/home"); } } // 替换已弃用的componentWillReceiveProps componentDidUpdate(prevProps) { if (this.props.loggedUser != null && prevProps.loggedUser !== this.props.loggedUser) { this.props.history.push("/home"); } } render() { return ( <div className="container"> <div className="container container__login"> <div className="login__section"> <img src={logo} alt="EMS Mars logo" className="login__section__logo" /> <h4>Welcome to Mars EMS! </h4> <p className="no-data" style={{ marginBottom: "-.25rem" }}> Please sign in with your Google account! </p> <br /> <br /> <GoogleLogin buttonText="log in with Google" className="btn-primary btn-login" onSuccess={this.onSuccess} onError={this.onFailure} /> <div className="intro"> <ul> <li> <Link to="/about">About</Link> </li> <li> <Link to="/privacy">Privacy Policy</Link> </li> <li> <Link to="/terms">Terms And Conditions</Link> </li> <li style={{ marginTop: ".6rem" }}>Made by Dzenis H.</li> <li>© {new Date().getFullYear()}</li> </ul> </div> </div> </div> </div> ); } } Login.propTypes = { loggedUser: PropTypes.string, getLoggedUser: PropTypes.func.isRequired, }; export default Login;
关键注意事项
- 确保你的Google Cloud Console项目中已启用Google Identity Services,且客户端ID的授权来源、重定向URI配置正确。
- 若不想使用
jwt-decode,也可调用Google People API获取用户信息,但解析JWT是更轻量的方案。 - 原代码中
componentWillMount和componentWillReceiveProps已被React官方弃用,替换为componentDidMount和componentDidUpdate可避免后续版本兼容性问题。
内容的提问来源于stack exchange,提问作者Dženis H.
相关产品推荐
相关产品推荐

