首页 > 解决方案 > 为什么我的信息传递滞后一个?

问题描述

我正在尝试编写一个简单的 React 应用程序,该应用程序需要用户使用 Google 登录,然后才能在应用程序中访问示例数据。我想在登录时显示一条欢迎消息,上面写着“欢迎,[姓名]!” 目前,此功能正在运行,但它落后于一次登录。

我的应用程序的开始状态

这就是应用程序在开始时的显示方式。

一次登录后的应用程序

这是应用程序在一次登录后出现的方式。请注意,它不是从用户的 Google 帐户获取名称,而是显示默认值“default”。

两次或多次登录同一帐户后的应用

但是,注销并重新登录后,应用程序正常运行,显示带有用户名的欢迎消息。我尝试使用其他帐户登录,但延迟仍然存在,即使用 Naomi 登录时显示“默认”,使用 Ally 登录时显示“Naomi”,注销并重新登录 Ally 后显示“Ally”。

我已经尝试在信息传递之前将带有用户名(userName)的变量记录到控制台,并且它似乎在登录完成后触发,但我不确定为什么。

我希望相关的代码如下。

import React from 'react';
import Login from './Login';

var userName = "default";

class LoginButton extends React.Component {

 // some other code here

  onSignIn = googleUser => {
    this.toggleLoggedIn();

    let user = googleUser.getBasicProfile();
    let id_token = googleUser.getAuthResponse().id_token;
    userName = user.getName(); //I try to grab the name from the user's account and assign it to userName

    console.log('google user obj', user);
    {/*console.log('google_id_token', id_token);*/}
    console.log('Name:', userName); //This properly logs the correct userName to the console

  };

  // some other code here

  render() {
    console.log(this.state.isLoggedIn);
    console.log(userName); //this incorrectly logs the userName lagged by one
    // noinspection CheckTagEmptyBody
    return (
      <div>
      <Login isLoggedIn={this.state.isLoggedIn} name={userName}/> //this passes the incorrect userName
        <div id="my-signin2"></div>
        <br />
        {this.state.isLoggedIn && (
          <button style={{ width: 200, height: 40, textAlign: 'center' }} onClick={this.logout}>
            Logout
          </button>
        )}
      </div>
    );
  }
}

任何帮助将非常感激。

标签: reactjs

解决方案


我的问题是this.toggleLoggedIn();

将它移到 onSignIn 功能块的末尾解决了我的问题。

    onSignIn = googleUser => {
    console.log("Sign in successful");
    let user = googleUser.getBasicProfile();
    userName = user.getName();
    this.toggleLoggedIn();
  };

推荐阅读