首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >反应谷歌登录

反应谷歌登录
EN

Stack Overflow用户
提问于 2018-08-23 10:46:53
回答 3查看 2.1K关注 0票数 1

我正在使用react谷歌登录(https://www.npmjs.com/package/react-google-login)工具登录,为我的应用程序提供谷歌登录功能。按照页面上的手册,我最终使用了以下代码。

代码语言:javascript
复制
<GoogleLogin
   clientId="xxx.apps.googleusercontent.com"
   onSuccess={this.responseGoogle.bind(this)}
   onFailure={this.responseGoogle.bind(this)}
   tag={'span'}
   className={"google-button-wrapper"}
   >
   <Button id={'google-button'} basic
      color='google plus'>
      <Icon name='google plus'/>
      Google Plus
   </Button>
</GoogleLogin>

问题是,即使不单击按钮,登录操作也会被触发。这发生在刷新页面之后。

我发现了以下可疑的情况:

刷新页->打开登录页=触发 刷新页面->打开登录页->再次打开不同站点->登录=第一次触发,第二次没有触发。 刷新页->打开登录页->打开注册页=在登录页上触发,而不是在注册页面上触发,即使有相同的代码片段。

我用的是React v ^16.3.2,有什么想法吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-08-23 10:48:53

尝试在onSuccess和onFailure中使用箭头函数,不要在这里绑定它们。更好的做法是在构造函数上绑定函数。

票数 5
EN

Stack Overflow用户

发布于 2020-12-02 16:11:43

我希望这能解决你的问题

代码语言:javascript
复制
import { GoogleLogin, GoogleLogout } from 'react-google-login';


const CLIENT_ID = '<client_id>';


class GoogleBtn extends Component {
   constructor(props) {
    super(props);

    this.state = {
      isLogined: false,
      accessToken: ''
    };

    this.login = this.login.bind(this);
    this.handleLoginFailure = this.handleLoginFailure.bind(this);
    this.logout = this.logout.bind(this);
    this.handleLogoutFailure = this.handleLogoutFailure.bind(this);
  }

  login (response) {
    if(response.accessToken){
      this.setState(state => ({
        isLogined: true,
        accessToken: response.accessToken
      }));
    }
  }

  logout (response) {
    this.setState(state => ({
      isLogined: false,
      accessToken: ''
    }));
  }

  handleLoginFailure (response) {
    alert('Failed to log in')
  }

  handleLogoutFailure (response) {
    alert('Failed to log out')
  }

  render() {
    return (
    <div>
      { this.state.isLogined ?
        <GoogleLogout
          clientId={ CLIENT_ID }
          buttonText='Logout'
          onLogoutSuccess={ this.logout }
          onFailure={ this.handleLogoutFailure }
          render={renderProps => (
            <Button onClick={renderProps.onClick} size="small">Logout</Button>)}
        />
           : <GoogleLogin
          clientId={ CLIENT_ID }
          buttonText='Login'
          onSuccess={ this.login }
          onFailure={ this.handleLoginFailure }
          cookiePolicy={ 'single_host_origin' }
          responseType='code,token'
          render={renderProps => (
            <Button onClick={renderProps.onClick}size="small">Login</Button>)}
        />
      }
      

    </div>
    )
  }
}

export default GoogleBtn;
票数 0
EN

Stack Overflow用户

发布于 2022-01-18 11:22:40

我也面临着同样的问题。结果是,如果您登录一次,然后刷新页面而不注销,则会触发登录操作,而无需单击按钮,因为登录状态将保持不变。

尝试注销,然后刷新页面。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51984016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档