reactjs - 为什么我的信息传递滞后一个?
问题描述
我正在尝试编写一个简单的 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>
);
}
}
任何帮助将非常感激。
解决方案
我的问题是this.toggleLoggedIn();
将它移到 onSignIn 功能块的末尾解决了我的问题。
onSignIn = googleUser => {
console.log("Sign in successful");
let user = googleUser.getBasicProfile();
userName = user.getName();
this.toggleLoggedIn();
};
推荐阅读
- html - 如何阻止我的滚动条推动我的标题?
- scala - Scala:错误:未找到:值 MutableList val ReviewsList = MutableList [Review]()
- facebook - Facebook 数据删除请求回调
- react-native - 多个navigation.push同一个屏幕总是到列表的最后一个
- pandas - 当要拆分的字符串数量不确定时,在分隔符上拆分数据框列
- ajax - .net 核心中的 ej-grid 网格在 ajax 调用后自动生成
- reactjs - “CI=false npm run build”是什么意思,不将警告视为 Netlify 或 Vercel 上的错误?
- c++ - 使用 16 位计数器检测多个窗口/轨道是否与单个窗口重叠
- c++ - 通过引用函数传递数组
- ios - .fullScreenCover 始终打开相同的详细信息页面